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

-

Other posts:

Utils.CheckNull(obj); if (this.GetType() != obj.Get­Type()) re­turn false; DateSpan other = obj as DateSpan; re­turn 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.

Tags

6 Comments

Comments

David V. Corbin

2007-12-28T18:53:36Z

Why are you ig­nor­ing the power of Guidance Automation to cre­ate all of the classes?????

Shouldn’t you sim­ply re­turn false for equal­ity if the other value is null in­stead of throw­ing?  

David: be­cause I barely know what it is ;-)
Anyhow, I think there is a sim­pler so­lu­tion. I’ll post it later.
Onovotny: yes, that is usu­ally the rec­om­mended way. In my case, I don’t want for these ob­jects to ever be null. If one of them is null, it means that there is some­thing wrong in my app and I want to know it. Hence the ex­cep­tion.

Charlie Calvert's Community Bl

2008-01-03T02:13:41Z

Welcome to the thirty-eighth Community Convergence. These posts are de­signed to keep you in touch with

Tales from the Evil Empire

2008-01-16T18:36:55Z

For some rea­son, there’s been a lot of buzz lately around im­mutabil­ity in C#. If you’re in­ter­ested in