Monday, July 30, 2012

Struct vs Class in C#

A while ago we had some discussions on our team on a struct vs class.  Here is a list of the differences

Struct VS Class

  • Structs and Classes both inherit from System.Object 
  • Structs cannot inherit from other classes. I would guess this is why there not used as often 
  • Structs live in the stack and classes lives in the heap 
  • Structs are value type and classes are reference type 
  • Structs do not require garbage collection, they go away when the method comes off the top of the stack 
  • Structs live in the stack window of the method they are declared 
  • Structs go to the heap if they are declared as member variables 
  • Structs don’t have pointers so they save memory Class have pointers so the memory address to the class in the heap takes up memory 
  • You don’t have to use the new keyword with a struct, but if you don’t the structs members will be null and not initialized 
  • Classes smaller than 16k can be more efficient as structs 
  • Structs can implement interfaces 
  • Structs constructors must have parameters public foo(string pParam1) ok but no foo() 
  • You can control the layout of the struct in memory on the stack using the StructlayoutAttribute attribute on a struct
 References
C Sharp Corner
MSDN Heap and Stack
Struct Tutorial
Struct Attribute