Wouldn't it be nice to have a type variable referring to the class's instance.

Posted by user93197 on Stack Overflow See other posts from Stack Overflow or by user93197
Published on 2011-01-04T14:51:19Z Indexed on 2011/01/04 14:53 UTC
Read the original article Hit count: 182

Filed under:
|

I often have a pattern like this:

class VectorBase<SubClass, Element>
    where SubClass : VectorBase<SubClass, Element>, new()
    where Element : Addable<Element>
{
    Element[] data;

    public VectorBase(Element[] data)
    {
        this.data = data;
    }

    public SubClass add(SubClass second)
    {
        Element[] newData = new Element[data.Length];
        for (int i = 0; i < newData.Length; i++)
        {
            newData[i] = data[i].add(second.data[i]);
        }
        SubClass result = new SubClass();
        result.data = newData;
        return result;
    }

}

class VectorInt : VectorBase<VectorInt, Int32>
{
}

class MyInt : Addable<MyInt>
{
    int data;

    public MyInt(int data)
    {
        this.data = data;
    }

    public MyInt add(MyInt t)
    {
        return new MyInt(data + t.data);
    }
}

interface Addable<T>
{
    T add(T t);
}

But I would rather just have:

class VectorBase2<Element> where Element : Addable<Element>
{
    Element[] data;

    public VectorBase(Element[] data)
    {
        this.data = data;
    }

    public SubClass add(SubClass second)
    {
        Element[] newData = new Element[data.Length];
        for (int i = 0; i < newData.Length; i++)
        {
            newData[i] = data[i].add(second.data[i]);
        }
        SubClass result = new SubClass(data);
        return result;
    }

}

class VectorInt2 : VectorBase2<Int32>
{
}

Why not make the subclass type available to all classes? Is this technically impossible?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics