A C# library to write functional code - Part III - Records

Tags: csharp @ 2008/04/04

Other posts in the series:

    This abstract class has a field of type STuple:
    
    <pre class="code"><span style="color:rgb(0,0,255);">protected</span> <span style="color:rgb(0,0,255);">readonly</span> <span style="color:rgb(43,145,175);">STuple</span>&lt;T1, T2&gt; state;

    What is a STuple? Well it is exactly the same as the Tuple described in Part II, but coded as a struct instead of a class. The reason to use a struct is to not allocate an additional object on the stack. This allows this solution to be as &#8216;performant' as simply having coded the fields on the class itself. Or at least I think so
    
    The Record class also has a constructor that simply initialize the STuple:
    
    <pre class="code"><span style="color:rgb(0,0,255);">public</span> Record(T1 t1, T2 t2) { state = <span style="color:rgb(43,145,175);">F</span>.STuple(t1, t2); }</pre>
    
    <pre class="code"><font face="Verdana">where</font></pre>
    
    <pre class="code"><span style="color:rgb(0,0,255);">internal</span> <span style="color:rgb(0,0,255);">static</span> <span style="color:rgb(43,145,175);">STuple</span>&lt;T1, T2&gt; STuple&lt;T1, T2&gt;(T1 t1, T2 t2) {
        <span style="color:rgb(0,0,255);">return</span> <span style="color:rgb(0,0,255);">new</span> <span style="color:rgb(43,145,175);">STuple</span>&lt;T1, T2&gt;(t1, t2);
    }</pre>
    
    The Equals method is very much the same as the Tuple's one, just delegating to the same DSEqual function that checks equality for Tuples.
    
    <pre class="code"><span style="color:rgb(0,0,255);">public</span> <span style="color:rgb(0,0,255);">override</span> <span style="color:rgb(0,0,255);">bool</span> Equals(<span style="color:rgb(0,0,255);">object</span> right) {
        <span style="color:rgb(43,145,175);">Utils</span>.CheckNull(right);
        <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">object</span>.ReferenceEquals(<span style="color:rgb(0,0,255);">this</span>, right))
            <span style="color:rgb(0,0,255);">return</span> <span style="color:rgb(0,0,255);">true</span>;
        <span style="color:rgb(0,0,255);">if</span> (<span style="color:rgb(0,0,255);">this</span>.GetType() != right.GetType())
            <span style="color:rgb(0,0,255);">return</span> <span style="color:rgb(0,0,255);">false</span>;
        <span style="color:rgb(0,0,255);">var</span> rightT = right <span style="color:rgb(0,0,255);">as</span> <span style="color:rgb(43,145,175);">Record</span>&lt;T1, T2&gt;;
        <span style="color:rgb(0,0,255);">return</span> <span style="color:rgb(43,145,175);">F</span>.DSEquals(<span style="color:rgb(0,0,255);">this</span>.state, rightT.state);
    }</pre>
    
    That's it. Not too difficult as most of the implementation is based on the Tuple's code. Next post will hopefully be more interesting. It is about Type Unions.