Enum types

Learn how Ice enumerations are mapped to C#

An Ice enumeration maps to a public C# enumeration with the same name, and each Ice enumerator maps to the C# enumerator with the same name. For example:

ice
enum Fruit { Apple, Pear, Orange }
C#
enum Fruit { Apple, Pear, Orange }

The Ice compiler generates extension methods to encode and decode instances of each enum:

  • EncodeName to encode an enum instance
  • DecodeName to decode an enum instance

With our Fruit example, we get:

C#
public static class FruitIceEncoderExtensions
{
public static void EncodeFruit(this ref IceEncoder encoder, Fruit value) => ...
}
public static class FruitIceDecoderExtensions
{
public static Fruit DecodeFruit(this ref IceDecoder decoder) => ...
}

The Ice compiler also generates an extension method AsName to convert an int value into an enumerator.

With our Fruit example:

C#
public static class FruitIntExtensions
{
public static Fruit AsFruit(this int value) => ...
}

This conversion fails and throws [InvalidDataException] when the value does not correspond to any enumerator of the Fruit enumeration.

The "cs:attribute"cs-attribute metadata directive adds the specified C# attribute to the mapped C# enum. You can use it to add the FlagsAttribute to the mapped C# enum. For example:

ice
enum MultiHue
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8
}
C#
[Flags]
public enum MultiHue
{
None = 0,
Black = 1,
Red = 2,
Green = 4,
Blue = 8,
}

The Flags attribute is moderately useful with IceRPC since the decoding code only allows values that match known enumerators. For example, you won't be able to decode 6 for Red and Green since 6 doesn't correspond to any enumerator.

Was this page helpful?

CookiesYour privacy
This website uses cookies to analyze traffic and improve your experience.
By clicking "Accept," you consent to the use of these cookies. You can learn more about our cookies policy in our Privacy Policy.