When should I use a struct instead of a class?

后端 未结 15 2130
臣服心动
臣服心动 2020-11-22 13:00

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

相关标签:
15条回答
  • 2020-11-22 13:25

    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,

    0 讨论(0)
  • 2020-11-22 13:31

    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:

    1. Is the main responsability of the type data storage?
    2. Is its public interface defined entirely by properties that access or modify its data members?
    3. Are you sure your type will never have subclasses?
    4. Are you sure your type will never be treated polymorphically?

    If you answer 'yes' to all 4 questions: use a struct. Otherwise, use a class.

    0 讨论(0)
  • 2020-11-22 13:31

    As @Simon said, structs provide "value-type" semantics so if you need similar behavior to a built-in data type, use a struct. Since structs are passed by copy you want to make sure they are small in size, about 16 bytes.

    0 讨论(0)
提交回复
热议问题