Hello

I've read plenty about how you can create unions in C# with structs and attributes to overlap the storage of, say, an int and a float where you know they won't be used at the same time. You are not allowed to overlap value types and reference types so that you cannot corrupt your references. However, you are allowed to overlap one reference type with another, and it seems to me this can lead to the same problems, but my .NET 2.0 compiler does not mind me doing it.

For example, it seems to me the following code corrupts memory by following a pointer (reference) which cannot contain a meaningful address. It is not considered unsafe by the compiler though. Is this correct? Or have I made a mistake? Can anyone verify what's going on?

Thanks in advance


class Program
{
static void Main(string[] args)
{
Union union = new Union();
union.objectWithValueMember = new ClassWithValueMember();
union.objectWithValueMember.value = 252455;

union.objectWithReferenceMember.reference.x = 5;

// Uh-oh: objectWithReferenceMember does not point
// to an instance of ClassWithReferenceMember.
// What exactly was the ".x" we just assigned to?
// (No error was thrown.)
}
}

[StructLayout(LayoutKind.Explicit)]
struct Union
{
[FieldOffset(0)]
public ClassWithValueMember objectWithValueMember;
[FieldOffset(0)]
public ClassWithReferenceMember objectWithReferenceMember;
}

class ClassWithValueMember
{
public int value;
}

class ClassWithReferenceMember
{
public ReferencedClass reference;
}

class ReferencedClass
{
public int x;
}