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

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

    I do not agree with the rules given in the original post. Here are my rules:

    1) You use structs for performance when stored in arrays. (see also When are structs the answer?)

    2) You need them in code passing structured data to/from C/C++

    3) Do not use structs unless you need them:

    • They behave different from "normal objects" (reference types) under assignment and when passing as arguments, which can lead to unexpected behavior; this is particularly dangerous if the person looking at the code does not know they are dealing with a struct.
    • They cannot be inherited.
    • Passing structs as arguments is more expensive than classes.

提交回复
热议问题