piątek, 11 września 2009

My virtual static implementation

What I want is to be able to write code like this:

public T Create<T>() where T : new(string)

{

    return new T("something");

}

or this:

public interface IConverter<Tin, Tout>

{

    static Tout Convert(Tin value);

}

 

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>

{

    return TConverter.Convert(value);

}

but current (4.0) version of C#/CLR doesn’t allow me to do it, so I was forced to think about substitute solution.

If we think about virtual methods we need class that has them and we need instance of this class.

public class IntStringConverter : IConverter<int, string>

{

    public static readonly IntStringConverter Instance = new IntStringConverter();

    public virtual string Convert(int value)

    {

        return value.ToString();

    }

}

But this gives us nothing because we need to know exact type. So I’ve created following class

public static class Static<T> where T : new()

{

    private static bool initilized;

    private static T value;

 

    public static T Value

    {

        get

        {

            if (!initilized)

            {

                value = new T();

                initilized = true;

            }

            return value;

        }

    }

}

to use it instead of Instance field.

And now I can write Convert method like this:

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>, new()

{

    return Static<TConverter>.Value.Convert(value);

}

or Create method

public interface INew<T, T1>

{

    T New(T1 param1);

}

 

public static T Create<T, TFactory>() where TFactory : INew<T, string>, new()

{

    return Static<TFactory>.Value.New("something");

}

So my solution is to create one instance of my “virtual static” type and make sure all other classes can use it without tight coupling to some static field. Right now, all they need to know is Static<T> class.