The enum type System.Reflection.TypeAttributes
appears rather pathological. It carries the [Flags]
attribute and has no less than four synonyms for the constant zero. From Visual-Studio-generated "metadata":
#region Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll
#endregion
using System.Runtime.InteropServices;
namespace System.Reflection
{
//
// Summary:
// Specifies type attributes.
[ComVisible(true)]
[Flags]
public enum TypeAttributes
{
//
// Summary:
// Specifies that the class is not public.
NotPublic = 0,
//
// Summary:
// Specifies that class fields are automatically laid out by the common language
// runtime.
AutoLayout = 0,
//
// Summary:
// Specifies that the type is a class.
Class = 0,
//
// Summary:
// LPTSTR is interpreted as ANSI.
AnsiClass = 0,
// (followed by non-zero members...)
Why would anyone use four names for zero in an enum type which carries the FlagsAttribute
? It seems really crazy.
Look at the consequences:
var x = default(System.Reflection.TypeAttributes); // 0
var sx = x.ToString(); // "NotPublic"
var y = (System.Reflection.TypeAttributes)(1 << 20); // 1048576
var sy = y.ToString(); // "AutoLayout, AnsiClass, Class, BeforeFieldInit"
Here the string representation of x
, the zero value of the type, becomes "NotPublic"
. While the string representation of the non-zero y
becomes "AutoLayout, AnsiClass, Class, BeforeFieldInit"
. Regarding y
, note that it has only a single bit set (1<<20
), and the name BeforeFieldInit
alone accounts for that bit exactly. All the other three names, AutoLayout, AnsiClass, Class,
, contribute with zero to the value.
What is going on?
Why this design?
The ToString()
representation is largely irrelevant
This pattern is pretty common when some of the options are non-binary; for example, there are 3 possible options. In that scenario you might designate 2 bits to carry those 3 options (leaving 4 unused), and the "default" option would be (logically) 00
. This means that yes, there will be multiple synonyms for 0
.
Note: this might also happen in purely binary options, if the enum author wants to make it more explicit - because the caller doesn't need to know which are "on" and which are "off".
Basically, don't worry about ToString()