Tuesday, January 13, 2009

Classes vs. Structs

I took a test recently, one of those asking ridiculous C# syntax questions rather than trying to figure out if your brain works, but anyway, I got stuck at a question about structs and classes. What is the difference between them?

Credit must be given where it is due, I took the info from a dotnetspider article, by Dhyanchandh A.V. , who organised the answer to my question very well:
  • Classes are reference types and structs are value types. i.e. one cannot assign null to a struct
  • Classes need to be instantiated with the new keyword, structs need only be declared
  • When one instantiates a class, it will be allocated on the heap.When one instantiates a struct, it gets created on the stack
  • One works with the reference to a class, but directly with the struct
  • When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference
  • One cannot have instance Field initializers in structs
  • Classes can have explicit parameterless constructors. Structs cannot
  • Classes support inheritance. But there is no inheritance for structs, except structs can implement interfaces
  • Since struct does not support inheritance, the access modifier of a member of a struct cannot be protected or protected internal
  • It is not mandatory to initialize all fields inside the constructor of a class. All the fields of a struct must be fully initialized inside the constructor
  • A class can declare a destructor, while a struct cannot

What is the purpose of a struct, then? It seems to be only a primitive type of class. Well, it serves purposes of backward compatibility with C. Many C functions (and thus COM libraries) use structs as parameters. Also, think of the struct as a logical template over a memory location. One could use the same memory space of an Int32 under a struct { Int16 lo,hi }. Coming from an older and obsolete age, I sometimes feel the need to just read the memory space of a variable and be done with it. Serialization? Puh-lease! just grab that baby's memory and slap it over someone else's space! :)