Why do we need struct? (C#)

后端 未结 9 1926
盖世英雄少女心
盖世英雄少女心 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:36

    One of the main reasons is that, when used as local variables during a method call, structs are allocated on the stack.

    Stack allocation is cheap, but the big difference is that de-allocation is also very cheap. In this situation, the garbage collector doesn't have to track structs -- they're removed when returning from the method that allocated them when the stack frame is popped.

    • edit - clarified my post re: Jon Skeet's comment.

提交回复
热议问题