C# – What are the use-cases for IsLittleEndian in BitConverter class

bitconvertercendiannessnetvb.net

I was so happy when I discovered IsLittleEndian field in BitConverter. I thought of course it should be there and I should be able to specify whatever endian I like. Well, my happiness didn’t last long. Spent some time till found out that there is no way to set the field.
The field is readonly, and it is only set to true in static constructor:

static BitConverter()
{
    IsLittleEndian = true;
}

It is funny that the field is actually used in the code. For example ToInt32 method implementation looks like this:

if (IsLittleEndian)
{
     return (((numRef[0] | (numRef[1] << 8)) | (numRef[2] << 0x10)) | (numRef[3] << 0x18));
}
return ((((numRef[0] << 0x18) | (numRef[1] << 0x10)) | (numRef[2] << 8)) | numRef[3]);

So seems like the ToInt32 is perfectly capable to handle both little and big endians.

My question is: how come there is very useful piece of code that is already implemented and sitting there in the FCL, but there is no way to use it (unless you start messing with reflection of course)? Is it just because some developers didn’t meet the deadline and left the job half-done? Even if so, why the code is not available, but the field is?
I hope there is a good reason for this.

I want to make myself clear. I don't need a solution on how to handle big-endian values. I do have a solution. The solution is actually shown in my question.

Best Answer

Unfortunately the IsLittleEndian field is just there to inform you. But Jon Skeets MiscUtil library has a nice EndianBitConverter, that supports little and big endian. There are also endian-aware BinaryWriter/-Reader classes.

Here is the link: http://www.yoda.arachsys.com/csharp/miscutil/

Edit: sorry but I don't have a better explanation. I think that this should have been included in the framework and I guess the code is currently there, so that it is easy to port the Converter to another architecture.

But exposing that functionality is a tad more complex than just making the field public. The converter is static, so changing the flag effectively changes global state and in a multi-threaded scenario this would be disastrous. The way to go is probably to provide two BitConverter objects that you can instantiate and use locally (that's what MiscUtil does). This requires additional classes and/or interfaces, so maybe it was a deadline issue and just got dropped for the time being. Let's hope it is added some time later.