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:
- structs can have methods.
- 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.
Structs are on the Stack not the Heap so therefore they are thread safe, and should be used when implementing the transfer object pattern, you never want to use objects on the Heap they are volatile, you want in this case to use the Call Stack, this is a basic case for using a struct I am surprised by all the way out answers here,
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.
I am surprised I have not read at any of the previous answer this, which I consider the most crucial aspect :
I use structs when I want a type with no identity. For example a 3D point:
If you have two instances of this struct you don't care if they are a single piece of data in memory or two. You just care about the value(s) they hold.
Use a class if:
Use a structure if:
when you don't really need behavior, but you need more structure than a simple array or dictionary.
Follow up This is how I think of structs in general. I know they can have methods, but I like keeping that overall mental distinction.
Bill Wagner has a chapter about this in his book "effective c#" (http://www.amazon.com/Effective-Specific-Ways-Improve-Your/dp/0321245660). He concludes by using the following principle: