Cyrus enhances Optional<>


Cyrus just can’t stop!  First he Refactored Optional<>, basically to use a singleton for None<>


 



interface IOptional<A>


{


    A Value { get; }


}


class None<A> : IOptional<A>


{


    public static readonly IOptional<A> Instance = new None<A>();


 


    private None() { }


 


    A IOptional<A>.Value


    {


        get { throw new InvalidOperationException(); }


    }


}


class Some<A> : IOptional<A>


{


    readonly A value;


 


    public Some(A value)


    {


        this.value = value;


    }


 


    A IOptional<A>.Value


    {


        get


        {


            return value;


        }


    }


}


 


He kept getting annoyed with himself for having an interface with only one method (IOptional), as that’s a smell that you need a delegate.  I insisted that an interface is the right thing, because a delegate isn’t just a single-method interface – it also is just about “shape”.  That is, a method with the right signature can satisfy a matching delegate, but you can’t satisfy an interface with a class unless you actually inherit from that interface.


 


To put it another way: methods don’t inherit from delegates.


 


Or yet another: inheritance counts from something.


 


He finally agreed and let it be.


 

Comments (2)

  1. It seems a work-around to have to make a singleton manually out of None<A>.

    Now I have to write None<A>.Instance don’t I?

    The compiler/JIT should be able to tell that it could spare some memory/cpu by having all references point to the same instance, the same way it does constant/string folding.

    Isn’t there a way of making that happen, maybe by declaring that this class is read-only or something?

  2. Cyrus Najmabadi says:

    Unfortunately, as far as I know, there is no built in way in the C# language to declare that something is a singleton.

    My implementation of the singleton is also incorrect in that certain special actions (like serialization) might break the singleton contract by producing more thatn one instance of the None<> type.

    It would be interesting to see if would be possible to create an attribute or base class that would allow one to simply make a singleton just by subclassing or by adding that attribute.