IsLittleEndian field reports false, but it must be Little-Endian?

I wonder if this is a timing bug, perhaps related to "beforefieldinit"... how are you looking at the value? It is possible that the type-initializer (for BitConverter) isn't getting triggered by the VS debugger (which is peeking under the covers, so to speak). Especially since false is the default value for a field...

The IsLittleEndian static field is set in the static constructor; and the time that an initializer executes is... very hard to predict. If you are using a debugger, all bets are off. The only way to reliably check the value of this field is via code (when the CLR will run the initializer at some point before it is required):

bool isLittleEndian = BitConverter.IsLittleEndian;

Don't trust the debugger / watch windows etc.


Raymond Chen gives an expanded answer to the question here (mirror, with better formatting here).

The gist of it is that:

Reading a member from the debugger does not execute the code to initialize that member.

So when you look at the field in Visual Studio, it will report false because the static initializer has not yet run. However, if you use the field in code, the static initializer will run, causing the field to return the actual correct value.

Tags:

C#

Windows 7