As you might have already heard .Net is type safe. Specifically talking CLR provides type safety at runtime, some .Net languages (example: C#) work with CLR to provide type safety at compile time.
So what does the term type safe mean?
Let’s find what Wikipedia says:
In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behavior caused by a discrepancy between differing data types for the program’s constants, variables, and methods (functions), e.g., treating an integer (int) as a floating-point number (float). Blah blah blah..
Ok, Now we know that type safety has something to do with preventing the programmer from accessing the type as other than what it is.
Well, C# and CLR are pretty good in this, they work together to push you into the Pit of success. But, you need to be very careful when working with unsafe code. Unsafe code is a different world in which you lose all the type safety, memory safety, security etc. So, clearly chances of making mistakes in unsafe code is greater than safe code(code which doesn’t uses unsafe).
We’re not going to look at unsafe code here. There is one trap I can see without using unsafe code at all. It is not so common, but there it is.
You probably have learned union in academics while learning C and C++, but, in C# you probably don’t need this if you’re writing pure managed code, no Interop. Some of you might not even know that union do exist in .Net world, but they do exist.
I write managed code, To be honest, I’ve never found a use case for union in .Net(at the time of writing), I mean pure managed code, no Interop.
What this post has to do with Union? As we know that unions share same memory location to store multiple fields(one at a time), that’s where the trap is. Yes, CLR won’t stop you falling into the trap in this case, i.e you could break the type safety provided by CLR using unions. May be break isn’t the right word, you could call it as a caveat to be aware of. It doesn’t matter what you call, but there’s something to be aware of.
In above program we create a new instance
Union and set the
Builder field to new
StringBuilder. We’re not creating any instances of
String and assigning to
Text field, but you can access it. That’s the beauty of unions.
We’re interpreting the
StringBuilder as if it is
String which also means that something terribly went wrong.
Ideally as a managed programmer you would expect CLR to throw
InvalidCastException but above program erroneously prints some number as String.Length and
StringBuilder as the type of the object. If you recall, this clearly violates the definition of type safety from Wikipedia which we skimmed earlier.
This is not to say that CLR isn’t type safe rather it is possible to write erroneous code with C# even without unsafe context. So be careful while dealing with unions in .net.