Using struct and class - what's that all about?

0

Category :

Class allocates memory on the stack to hold a reference to a MyClass instance in future, it does not create an instance of MyClass, and you will have seen that before - when you try to use any property or method of a class and you get a "Object reference not set to an instance of an object" exception and your program crashes, it's because you created a variable, but didn't create or assign an actual instance to the variable.

Struct what this does is create a new instance of MyClass on the heap, and assign the reference to it to the variable mc. This is important, because the stack and the heap are different "types" of memory: the heap is a big "lump" of memory which is sorted out by the Garbage collector and all classes, methods and threads share it. The stack on the other hand is specific to a thread, and everything on the stack is discarded when you exit the method - which means that the mc variable is lost, but the data it references is not - if you have copied the reference to a variable outside the method, then you can still access it from the rest of your program.

When to use a Struct

CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

AVOID defining a struct unless the type has all of the following characteristics:
  1. It logically represents a single value, similar to primitive types (int, double, etc.).
  2. It has an instance size under 16 bytes.
  3. It is immutable.
  4. It will not have to be boxed frequently.

http://msdn.microsoft.com/en-us/library/ms229017%28v=vs.110%29.aspx
my thanks to:
http://www.codeproject.com/Articles/728836/Using-struct-and-class-whats-that-all-about

0 comments:

Post a Comment