Which is best for data store Struct/Classes?

后端 未结 9 1898
无人共我
无人共我 2020-11-30 05:29

We have seen lots of discussion in SO regarding the class vs struct in c#. Mostly ended with conclusions saying its a heap/stack memory allocation. And reco

9条回答
  •  不知归路
    2020-11-30 06:05

    I would make the choice based on the following criteria

    • reference type vs value type semantics. If 2 objects are only equal if they are the same object, it indicates reference type semantics => class. If the value of its members defines equality (e.g. 2 DateTimes are equal if both represent the same point in time even if they are 2 distinct objects), value type semantics => struct
    • Memory footprint of the object. If the object is huge and frequently allocated, making it a struct would consume the stack much faster, hence I'd rather have it as a class. On the contrary, I'd rather avoid the GC penalty for small value types; hence make them a struct.
    • can you make the object immutable? I find structs great for 'value objects' - from the DDD book.
    • Would you face some boxing-unboxing penalty based on the usage of this object? If yes, go for class.

提交回复
热议问题