Tuesday, June 12, 2018

.net - When should I use a struct instead of a class?



MSDN says that you should use structs when you need lightweight objects. Are there any other scenarios when a struct is preferable over a class?



Some people might have forgotten that:




  1. structs can have methods.


  2. structs cannot be inherited.



I understand the technical differences between structs and classes, I just don't have a good feel for when to use a struct.


Answer



MSDN has the answer:
Choosing Between Classes and Structures.



Basically, that page gives you a 4-item checklist and says to use a class unless your type meets all of the criteria.





Do not define a structure unless the
type has all of the following
characteristics:




  • 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.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...