A few days ago I was in a discussion with a friend of mine who interviewed for a senior level developer position. He mentioned that one of the questions he was asked in his technical interview was "Describe a scenario where you would use a Struct instead of a Class.". He told me he could not think of one. So this article is an attempt to both explain the differences between a Class and a Struct and also describe when a struct should be used instead of a class.
Reference Type vs. Value Type
One of the primary differences between a Class and a Struct is that a Class is a reference type and a Struct is a value type. What does this mean? Well, let's take a look at other value types. All of the primitive types such as int, bool, decimal etc. are value types. Value types are stored in the stack as a single space in memory whereas refernce types are created in memory and a reference to that space is also create. The reference type is always accessed via the reference and not directly. For example;
Point p1 = new Point(); //Point is a Struct
Form f1 = new Form(); //Form is a Class
Point p2 = p1;
Form f2 = f1;
In the above code example p2 is an independent copy of p1. If you were to change a value of a property of p2, p1 would not be affected. Whereas f2 is a copy of the refence to f1 there for f1 and f2 are both references to the same object in memory. If you were to change a value of a property of f2, f1 would also be changed.
Heap vs. Stack
The stack is a simple FILO (first in last out) memory structure. The Stack is a highly efficient memory structure that "bookmarks" the stack when a method begins execution, Dumps data into the stack during the method execution and once the method exection completes the stack is reset to the bookmark releasing all the method's allocated memory.
The heap is just the opposite. The heap can be considered, for lack of a better term, a random access memory structure. Objects can be allocated and deallocated in a random order. The heap requires the use of a memory manager and garbage collector to maintain it's structure.
When you instantiate a class the instance of the class itself is stored in the heap whereas the reference to the instance of the class is stored in the stack.
Form f1 = new Form();
The actual object created by the above code will be placed in the heap and the reference, f1, to that object is stored in the stack.
When to use a Struct
Keep the following rules in mind when using a struct:
- a struct should represent a single value
- a struct should have a memory footprint less than 16 bytes
- a struct should not be changed after creation.
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5