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

前端 未结 28 3097
予麋鹿
予麋鹿 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条回答
  •  萌比男神i
    2020-11-21 12:07

    Briefly, use struct if:

    1. your object properties/fields do not need to be changed. I mean you just want to give them an initial value and then read them.

    2. properties and fields in your object are value type and they are not so large.

    If that's the case, you can take advantage of structs for a better performance and optimized memory allocation as they use only stacks rather than both stacks and heaps (in classes)

提交回复
热议问题