Choosing between immutable objects and structs for value objects

后端 未结 11 1542
鱼传尺愫
鱼传尺愫 2020-12-13 15:07

How do you choose between implementing a value object (the canonical example being an address) as an immutable object or a struct?

Are there performance, semantic or

11条回答
  •  伪装坚强ぢ
    2020-12-13 15:52

    As a rule of thumb a struct size should not exceed 16 bytes, otherwise passing it between methods may become more expensive that passing object references, which are just 4 bytes (on a 32-bit machine) long.

    Another concern is a default constructor. A struct always has a default (parameterless and public) constructor, otherwise the statements like

    T[] array = new T[10]; // array with 10 values
    

    would not work.

    Additionally it's courteous for structs to overwrite the == and the != operators and to implement the IEquatable interface.

提交回复
热议问题