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 ha
I think the best answer is simply to use struct when what you need is a collection of properties, class when it's a collection of properties AND behaviors.
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.
Use a struct when you want value-type semantics instead of reference-type. Structs are copy-by-value so be careful!
Also see previous questions, e.g.
What's the difference between struct and class in .NET?
Hmm...
I wouldn't use garbage collection as an argument for/against the use of structs vs classes. The managed heap works much like a stack - creating an object just puts it at the top of the heap, which is almost as fast as allocating on the stack. Additionally, if an object is short-lived and does not survive a GC cycle, deallocation is free as the GC only works with memory that's still accessible. (Search MSDN, there's a series of articles on .NET memory management, I'm just too lazy to go dig for them).
Most of the time I use a struct, I wind up kicking myself for doing so, because I later discover that having reference semantics would have made things a bit simpler.
Anyway, those four points in the MSDN article posted above seems a good guideline.
In addition the the excellent answers above:
Structures are value types.
They can never be set to Nothing.
Setting a structure = Nothing , will set all its values types to their default values.
I would use structs when:
an object is supposed to be read only(every time you pass/assign a struct it gets copied). Read only objects are great when it comes to multithreaded processing as they don't requite locking in most cases.
an object is small and short-living. In such a case there is a good chance that the object will be allocated on the stack which is much more efficient than putting it on the managed heap. What is more the memory allocated by the object will be freed as soon as it goes outside its scope. In other words it's less work for Garbage Collector and the memory is used more efficient.