Monday 7 April 2014

Difference between Class and Struct

A struct is a construct that is almost identical to a class.
The major difference is that structs are value type objects while classes are reference type objects. This means that when you pass a struct object to a method, the method will receive a copy of the object and wont be able to make changes to it outside the method.
It is usually best to use classes instead of structs as there are many features of classes that aren't supported by struct objects. However it is not possible to pass a class object by value so if there is s special need to do this you may find struct more appropriate.

The limitations of structs are that they cannot have constructor methods without any arguments and they cannot extend classes nor can classes extend structs.

Because structs are value type objects, this means that they are stored in the stack. Whereas class objects are stored in the heap. Because struct objects are stored in the stack they will generally be slightly faster than class objects. It is best to avoid using large structs as there is a limited amount of space in the stack, you should only use structs for small constructs that need to be accessed quickly.

No comments:

Post a Comment