Last post Jun 23, 2011 10:41 AM by atconway
Jun 22, 2011 10:30 AM|threeo|LINK
classes vs structures in .Net
any opinions regarding whether it is better or advantageous to use one over the other?
(in terms of performance or usability etc)
Jun 22, 2011 10:44 AM|Jeev|LINK
Jun 22, 2011 10:47 AM|chandu123|LINK
Jun 22, 2011 10:51 AM|manishgvsharma2000|LINK
refer this kink
Jun 22, 2011 11:05 AM|frez|LINK
Use a struct if it is holding a small amount of data.
Structs are held on the stack so can be accessed quicker, classes are held on the heap with only a reference to it held on the stack, but you do not want to fill the stack with data by using it to hold 'large' structs.
Jun 22, 2011 11:15 AM|frez|LINK
Actually found a better answer on msdn here
Basically you would only choose a struct over a class if:
It logically represents a single value, similar to primitive types (integer, double, and so on).
It has an instance size smaller than 16 bytes.
It is immutable.
It will not have to be boxed frequently.
Jun 22, 2011 12:20 PM|threeo|LINK
Jun 23, 2011 10:41 AM|atconway|LINK
var1 & var2, using a class that just has these two properties is overkill and too heavy right?.
Not if that class has behavior, will need to be extended, inherited from, etc. If however you know it is a finite small structure that will always be a known type and not do any boxing and unboxing, then using a Structure might be more efficient.
I wouldn't look at it from a performance standpoint as much as the needs of your data. There are logical reasons for using a class or a struct. This is how you should define which type to use. From your description it sounds like using a structure may suffice.
Have a look at the following for some guidance: