Structures in C# & .Net

You are probably not sure why I’m writing post about structures in the Advanced C# category. I hope that by the end of the post you will be sure, because structures have some interesting attributes in .net that worth understanding, especially when writing high performance and low level code in C#.

Structures are value type

What does that mean? Let’s dive directly into an example:

struct Number  
{
  public int Value;
}

static void Main(string[] args)  
{
  Number n;
  n.Value = 5;

  Number n2 = n;
  Console.WriteLine("Value of n2 after copyied from n: {0}", n2.Value);

  n2.Value = 10;
  Console.WriteLine("Value of n2 after a change: {0}", n2.Value);
  Console.WriteLine("Value of n after the change to n2: {0}", n.Value);
}

Before showing you the result, let’s talk about some interesting points in this code, I didn’t initialize the n variable and didn’t get null reference exception, why is that? because when you create a structure variable it’s created on the stack, it’s not a pointer to memory on the heap. Now let’s take a look at the result:

2

Strange? doing the same with classes would show 10 for both n and n2, but with structures n keep the original value. Why? because it’s value type, it’s not like a class that when you are doing assignment you just copy the reference, you copy the entire structure. n and n2 are two different location on memory, when the assignment happen it just copied all the memory from n to n2, when we changed n2 the n didn’t change.

Deep Copy

So we know that every time we use assignment with structure we are actually coping memory, this copy thing can be a good for case when you want an object to have deep copy capability, instead of manual copy all the object and fields or using serialization solutions.

The rule for using structure for deep copy is that the structure will only hold primitives and other structures (which hold primitives), string will be copied as well but arrays won't be deep copeied.

Some example can be the memento pattern, which is a pattern when an object can go back to previous state, you can hold all the state of the object (which is a class) in a structure and when you start editing copy the structure to another field inside the class, when you want to rollback just copy the structure back to the main field.

Serialization

I think is the fastest way to serialize an object in .net, what I’m I talking about? because structure is a block of memory, you can copy this block of memory into a byte array, no serialization and no other stuff, just copy into a byte array and your are ready to save to a file, send with socket or write to a stream. How you do this? following is a short example:

int size = Marshal.SizeOf(n);  
byte[] bytes = new byte[size];

var handle = GCHandle.Alloc(n, GCHandleType.Pinned);  
IntPtr ptr = handle.AddrOfPinnedObject();

Marshal.Copy(ptr, bytes, 0, size);

handle.Free();  

What happened here? We got the memory location of the structure with line 4 & 5 (this trick is usually used with interop) then copied the memory to the byte array and released the pointer and handle.

comments powered by Disqus