Enum types

Learn how to define enumerations in Slice.

By default, when the code generated by the Slice compiler decodes an instance of an enumeration, it makes sure this instance corresponds to a known enumerator. This is the "checked" behavior: the decoding fails for a value with no matching enumerator.

You can also get the opposite behavior—unchecked—by prepending unchecked to your enumeration definition. For example:

Since ErrorCode is marked unchecked, the generated code will successfully decode an integral value without a matching enumerator.

A checked enumeration must have at least one enumerator, while an unchecked enumeration may have no enumerator at all. For example, the following enumeration is valid:

The Slice 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:

This conversion fails and throws InvalidDataException when the value does not correspond to any enumerator of the (checked) enum.

The cs::attribute attribute adds the specified C# attribute to the mapped C# enum. You typically use it to add the FlagsAttribute to the mapped C# enum. For example:

You can also apply cs::attribute to an enumerator to get the specified C# attribute on the mapped C# enumerator.

Was this page helpful?