When should I use a struct instead of a class?

2018-12-31 14:06发布

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.

标签: .net oop
14条回答
美炸的是我
2楼-- · 2018-12-31 14:55

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.

查看更多
浅入江南
3楼-- · 2018-12-31 14:58

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.

查看更多
登录 后发表回答