Saturday, July 07, 2007

Struct Vs Class in .Net

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:

Anonymous said...

All the explanations are very clear. Thanks alot for your good work. Keep going!!

Anonymous said...

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

@j said...

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

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape