Cyrus enhances Optional<>

Published 06 May 04 11:54 PM

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

# Julien Couvreur (Dumky) said on May 7, 2004 8:34 AM:
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?
# Cyrus Najmabadi said on May 7, 2004 3:54 PM:
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.
New Comments to this post are disabled

This Blog

Syndication

Page view tracker