Difference between Struct and Class
Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.
Choosing between struct and class
Use of structure in following condition is desirable.
When you have small data structure
Data Structure does not require to extent the functionality.
When you want to perform faster operation on data structure. (As structure are stored on stack, operation performed on it are faster.)
Use of class in following condition is desirable.
When you have complex data structure
Data Structure requires to extend functionality.
When you want to optimize memory usage. (As class is stored on heap, they are about to be garbage collected when no reference pointing to an object.)
What is the difference between instantiating structures with and without using the new keyword?
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.
3 comments:
All the explanations are very clear. Thanks alot for your good work. Keep going!!
Thanks for the article. Whilst it provides a general overview of the differences and a 'rule-of-thumb' for usage, it is far from exhaustive in both cases.
There are a number of articles that compare structs in more depth.
One thing that new coders tend to forget when deciding whether to use structs or classes is 'boxing/unboxing' and the performance overheads.
Although generics alleviate this to some extent, it should still be kept in mind when deciding which to use.
Anyway, keep up the good work.
Sunil
Post was good and well explained but if you could give an example also that how a struct can be instantiated with or without a new keyword that would be much more better.
Thanks,
@j
Post a Comment