Saturday, August 26, 2006

C# Classes Versus Structs

I will try to group here the differences and commonalities bewtween classes and structs.

Differences:

Classes are reference types, structs are value types.
Classes are allocated in the Heap, structs are allocated on the stack.
Class instances are passed to methods as references, a copy of the struct is passed to a method.
Classes can declare an explicit parameterless constructor, structs cannot declare an explicit parameterless constructor.
Class members can have initializers (private string s = "asd";) while struct members cannot have initializers (private string s;). They must be initialized in the constructor.
Classes cannot be instantiated without the use of the new operator, structs can be instantiated without the use of the new operator.
A struct cannot inherit from another struct or class (it inherits from object by default).
A struct cannot be the base of another class.


Commonalitites:

Both can implement interfaces.
You CAN call a parameterless constructor for both classes and structs (if the class has one defined; a struct always has it and it is implicit).

Struct usage guidelines (taken from http://www.awprofessional.com/articles/article.asp?p=423349&seqNum=2&rl=1):

DO NOT define a struct unless the type has all of the folloing characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

No comments: