Miicck Miicck - 2 months ago 8
C# Question

Passing derived type as argument to abstract class

I was wondering if it is possible to implement a similar signature to the below code in c#:

public abstract class baseClass
{
public abstract float function(derivedType a, derivedType b);
}

public class derived: baseClass
{
public override float function(derived a, derived b)
{
return something to do with a and b;
}
}


Hopefully it's clear what I'm trying to do from that, cheers.

Edit: I tried the below with no success, hopefully it might also clarify what I'm trying to do:

public abstract class baseClass
{
public abstract float function<T>(T a, T b) where T:baseClass;
}

public class derived: baseClass
{
public override float function<derived>(derived a, derived b)
{
return a.value + b.value;
}

public float value;
}


Apparently derived doesn't contain a definition for 'value' according to visual studio.

Edit, SOLUTION:

public abstract class baseClass<T> where T: baseClass<T>
{
public abstract float function(T a, T b);
}

public class derived : baseClass<derived>
{
public override float function(derived a, derived b)
{
return a.value + b.value;
}

public float value;
}


Thanks everyone for the help :)

Answer

If I understand you correctly what you are looking for, all you have to do is this:

public abstract class baseClass<T> where T : baseClass<T>
{
    public abstract float Foo(T a, T b);
}

public class derived : baseClass<derived>
{
    public override float Foo(derived a, derived b)
    {
        throw new NotImplementedException();
    }

    public float value;
}