~~ Offline ~~ theme Menu

Creating an immutable value object in C# - Part IV - A class with a special value

Other posts:

Utils.CheckNull(obj); if (this.GetType() != obj.GetType()) return false; DateSpan other = obj as DateSpan; return other.End == End && other.Start == Start; }

<pre class="code"><span style="color:rgb(0,0,255);">public</span> <span style="color:rgb(0,0,255);">static</span> <span style="color:rgb(43,145,175);">Boolean</span> <span style="color:rgb(0,0,255);">operator</span> ==(<span style="color:rgb(43,145,175);">DateSpan</span> v1, <span style="color:rgb(43,145,175);">DateSpan</span> v2) {
    <span style="color:rgb(43,145,175);">Utils</span>.CheckNull(v1);
    <span style="color:rgb(43,145,175);">Utils</span>.CheckNull(v2);
    <span style="color:rgb(0,0,255);">return</span> (v1.Equals(v2));
}</pre>

So now we have an immutable value object, represented as a class, with checks for nulls and a special value (not shown above because it is essentially the same as for structs). So, does this work?

It does, but it is cumbersome to write. And if it is too cumbersome, I already know that I'm not going to use it. I might start doing it, but I would soon give up. Are there ways to ease the pain?

One way would be to use snippets to help in writing the code. Snippets in this case have a couple of problems:

  * It is not easy to &#8216;snippify' the logic inside &#8216;Equals', &#8216;GetHashcode' and such
  * It makes easy to write the code, but still it is hard to read it and maintain it

In the next post we'll look at a better solution.
Top