Can't cast to generic type c#

I have the following scenario

public class A
{
}

public class BA : A
{

}

//other subtypes of A are defined

public class AFactory
{
    public T Create<T>() where T : A
    {
        //work to calculate condition
        if (condition)
            return new BA();
        //return other subtype of A
    }
}

The following compilation error is thrown:

Error CS0029 Cannot implicitly convert type 'B' to 'T'

What's wrong?

Jon Skeet
people
quotationmark

Well the cast could easily fail. Suppose I have:

public class AB : A {}

B b = new B();
AB ab = b.Create<AB>();

That would end up trying to assign a B reference to a variable of type AB. Those are incompatible.

It sounds like you probably shouldn't make Create a generic method. Or maybe you should make A generic:

public abstract class A<T> where T : A
{
    public abstract T Create();
}

public class B : A<B>
{
    public override B Create()
    {
        return new B();
    }
}

That would work - but we don't know what you're trying to achieve, so it may not actually help you.

Alternatively you could keep your current design, but use:

public T Create<T>() where T :  A
{
    return (T) (object) new B();
}

That will then fail if you call Create with a type argument of anything other than object, A or B, which sounds a little odd to me...

people

See more on this question at Stackoverflow