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

南楼画角 提交于 2019-12-05 03:39:18

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.

Alexander Tsvetkov

Actually it might be better to refactor the code so that you don't have to use switch statements at all. Although the construction itself is not an anti-pattern, but it is commonly accepted practice to use polymorphism instead. Here is another discussion of the ways to get rid of switch.

It seems to me that all the possible videoformats you're working with could be a classic example for using enumerations. I really don't see a problem to extend your enumeration with new values when some other formats will be added. Yes, the important thing we need to be sure that any VideoFormat used in the program should fit the enumeration. But possibly it won't be a disadvantage.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!