When should I use a struct rather than a class in C#?

前端 未结 28 2651
予麋鹿
予麋鹿 2020-11-21 11:55

When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to

28条回答
  •  礼貌的吻别
    2020-11-21 12:03

    Following are the rules defined at Microsoft website:

    ✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

    ❌ AVOID defining a struct unless the type has all of the following characteristics:

    It logically represents a single value, similar to primitive types (int, double, etc.).

    It has an instance size under 16 bytes.

    It is immutable.

    It will not have to be boxed frequently.

    for further reading

提交回复
热议问题