Why do we need struct? (C#)

后端 未结 9 1923
盖世英雄少女心
盖世英雄少女心 2021-02-05 21:18

To use a struct, we need to instantiate the struct and use it just like a class. Then why don\'t we just create a class in the first place?

9条回答
  •  情话喂你
    2021-02-05 21:24

    the difference is that a struct is a value-type I've found them useful in 2 situations

    1) Interop - you can specify the memory layout of a struct, so you can guarantee that when you invoke an unmanaged call.

    2) Performance - in some (very limited) cases, structs can be faster than classes, In general, this requires structs to be small (I've heard 16 bytes or less) , and not be changed often.

提交回复
热议问题