Immutable class vs struct

前端 未结 4 740
执念已碎
执念已碎 2021-02-03 23:55

The following are the only ways classes are different from structs in C# (please correct me if I\'m wrong):

  • Class variables are references, while struct variables
4条回答
  •  [愿得一人]
    2021-02-04 00:27

    From MSDN;

    Classes are reference types and structures are value types. Reference types are allocated on the heap, and memory management is handled by the garbage collector. Value types are allocated on the stack or inline and are deallocated when they go out of scope. In general, value types are cheaper to allocate and deallocate. However, if they are used in scenarios that require a significant amount of boxing and unboxing, they perform poorly as compared to reference types.

    Do not define a structure unless the type has all of the following characteristics:

    • It logically represents a single value, similar to primitive types (integer, double, and so on).

    • It has an instance size smaller than 16 bytes.

    • It is immutable.

    • It will not have to be boxed frequently.

    So, you should always use a class instead of struct, if your struct will be more than 16 bytes. Also read from http://www.dotnetperls.com/struct

提交回复
热议问题