Create Value Object in C#


How to create a value object (pattern in Domain Driven Design) in C#


Create a class that abstracts away (encapsulate) ‘data’ in your domain and provide methods to work on it. Below is a class I don’t consider a good Value Object:

However, the class below is what I do consider a good Value Object:


The difference between above two Gender classes is that the first one isn’t encapsulating its internal representation i.e. how it holds the gender information in an enum.

Exposing internal state as properties isn’t the same as encapsulating state, although this is a common misunderstanding. Good encapsulation is when the internals (data/behaviour) are abstracted away from the client by providing domain specific behaviour.

The second Gender class does that by providing IsMale and IsFemale properties. This way if the internal representation change, say from enum to string, then the client doesn’t need to change/know:

Client code (the Test in this case) doesn’t need to change even though the internal representation of the class has changed.

Source Code


Leave a Reply