0

Let's say we have this enum:

[Flags]
public enum SerialBaudRate {
    Default = _11520bps,
    _9600bps   = 0,
    _19200bps  = 1,
    _11520bps  = 2,
    _230400bps = 3,
    _460800bps = 4,
}

and we want to print out the enum value using interpolated string:

Console.WriteLine($"SerialBaudRate: {SerialBaudRate._11520bps}");

Console output will be:

SerialBaudRate: Default

How to make Default value name to be ignored then printing it to the string and use (print) _11520bps instead ?

Vinigas
  • 464
  • 5
  • 18
  • 3
    When using [Flags] the enum values should be uniquely bitmapped. If your enum variable has a value of 3 - that is the equivalent of the enum with value 1 OR'd with the enum with value 2 - in your case _19200bps | _11520bps. – PaulF Mar 06 '18 at 14:19
  • 3
    The [documentation](https://msdn.microsoft.com/en-us/library/16c1xs4z%28v=vs.110%29.aspx) explicitly states "If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return." This is confirmed by [the reference source](https://referencesource.microsoft.com/#mscorlib/system/enum.cs). There is no attempt to prefer one name over another. – Raymond Chen Mar 06 '18 at 14:20
  • You could write your own [TypeConverter](https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx) class or method to ensure you get the right string back. – PaulF Mar 06 '18 at 14:28

1 Answers1

2

UsingEnum.GetNames will print the name of the enum:

Console.WriteLine($"SerialBaudRate: {Enum.GetName(typeof(SerialBaudRate),SerialBaudRate._11520bps)}");
richej
  • 834
  • 4
  • 21
  • There is no guarantee that `GetName()` will return the expected result. See https://www.ideone.com/qYa551: it returns `SameValue.Default` for `SameValue.Two`. See [Remarks](https://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx): _"If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member."_ – CodeCaster Mar 06 '18 at 14:26