Ilya Ivanov
Ilya Ivanov

Reputation: 123

Cannot implicitly convert derived type to base generic type

The following code is not compiled with

error CS0029: Cannot implicitly convert type 'CSConsoleTest.Derived' to 'T'.

Is it a compiler bug or what is the reason?

public class Base
{
    public Derived Derived;
}
public class Derived : Base
{
}
class Program
{
    public static void Func<T>(T obj) where T : Base
    {
        obj = obj.Derived;
    }
}

Upvotes: 1

Views: 1161

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

T could be any class derived from T not always base class. for example:

public class Derived1 : Base
{
}
public class Derived2 : Base
{
}

T could be Derived1 or Derived2 or Base.

you cannot cast Derived1 to Derived2 that's why compiler refuses implicit cast.

obj = obj.Derived as T; // safe explicit cast.

Apart from that I do not suggest having child class inside base class. if you tell what you have in mind perhaps we can give you the right path.

Upvotes: 1

Related Questions