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

前端 未结 28 2646
予麋鹿
予麋鹿 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:19

    Whenever you:

    1. don't need polymorphism,
    2. want value semantics, and
    3. want to avoid heap allocation and the associated garbage collection overhead.

    The caveat, however, is that structs (arbitrarily large) are more expensive to pass around than class references (usually one machine word), so classes could end up being faster in practice.

提交回复
热议问题