I'm trying to use the code from this article: Creating Fake Enums, but I can't figure out why it doesn't work.
This code:
Console.WriteLine(FakeEnum.One.FriendlyName);
Console.WriteLine(FakeEnum.Four.FriendlyName);
generates an exception:
System.TypeInitializationException was unhandled
Message="The type initializer for 'FakeEnum' threw an exception."
Source="FakeEnum1"
TypeName="FakeEnum"
StackTrace:
at FakeEnum1.Program.Main(String[] args) in ..\Test\FakeEnum1\Program.cs:line 26
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
Source="FakeEnum1"
StackTrace:
at FakeEnum.op_Equality(FakeEnum a, FakeEnum b) in ..\Test\FakeEnum1\FakeEnum.cs:line 158
at FakeEnum.ToString(String format) in ..\Test\FakeEnum1\FakeEnum.cs:line 31
at FakeEnum.ToString() in ..\Test\FakeEnum1\FakeEnum.cs:line 25
at FakeEnum..ctor(Int32 value, String friendlyName) in ..\Test\FakeEnum1\FakeEnum.cs:line 171
at FakeEnum..ctor(Int32 value) in ..\Test\FakeEnum1\FakeEnum.cs:line 165
at FakeEnum..cctor() in ..\Test\FakeEnum1\FakeEnum.cs:line 13
If I comment the members declared with the (int)
constructor, everything else works:
public static readonly FakeEnum One = new FakeEnum(1, "One's Friendly Name");
public static readonly FakeEnum Two = new FakeEnum(2, "Two's Friendly Name");
public static readonly FakeEnum Three = new FakeEnum(3, "Three's Friendly Name");
//public static readonly FakeEnum Four = new FakeEnum(4);
//public static readonly FakeEnum Five = new FakeEnum(5);
//public static readonly FakeEnum Six = new FakeEnum(6);
Now, if I make the constructors public
, the following code works just fine:
FakeEnum a = new FakeEnum(14, "1 4");
FakeEnum b = new FakeEnum(28);
Console.WriteLine(a.FriendlyName);
Console.WriteLine(b.FriendlyName);
I just run out of ideas - what am I missing, and what generates the exception when using the original code?