Custom structure/type that can be used with switch()

c#, object-model, switch-statement, value-type

Solution

UPDATE: This answer is no longer entirely accurate due to new rules for switch statements in C# 7. See the C# 7 documentation for details.

Is there any way I can make use of this type and the static values directly in a switch block

No. The governing type of a switch statement must be one of sbyte, byte, short, ushort, int, uint, long, ulong, char, bool, any enum, the nullable value types of any of those, or string. And the constants used in the case labels must be compile time constants compatible with the governing type.

Problem

One of my projects has a value type/struct that represents a custom identifier string for a video format. In this case, it's going to contain a content type string, but that can vary. I've used a struct so it can be strongly type when it's passed around, and perform some sanity checks on the initial string value. The actual string value could be anything and provided by external plugins libraries so a numeric `enum` doesn't apply. ``` public struct VideoFormat { private string contentType; public VideoFormat(string contentType) { this.contentType = contentType; } public string ContentType { get { return this.contentType; } } public override string ToString() { return this.contentType; } // various static methods for implicit conversion to/from strings, and comparisons } ``` As there are a few very common formats, I've exposed these as static read only fields with default values. ``` public static readonly VideoFormat Unknown = new VideoFormat(string.Empty); public static readonly VideoFormat JPEG = new VideoFormat("image/jpeg"); public static readonly VideoFormat H264 = new VideoFormat("video/h264"); ``` This seems to work on most cases except a switch block where it says the value has to be a constant. Is there any way I can make use of this type and the static values directly in a switch block without switching on the internal member or the `.ToString()` override? Is there a better overall method to do this without using a design time specified `enum` with numeric values or plain string constants?

Original source

Related problems