0

Why is the following bloc wrong?

    public interface IBase { }
    public class ClassX : IBase
    {
    }

    public class ClassY
    {
        public static ClassX FunctionReturnX() { return new ClassX(); }
    }

    public class ClassZ<TGeneric> where TGeneric : IBase
    {
        Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right

        Func<TGeneric> funcGeneric = ClassY.FunctionReturnX; //Wrong
    }
Aly Elhaddad
  • 1,913
  • 1
  • 15
  • 31

2 Answers2

1

Because ClassX is definitely a IBase, but it might not be TGeneric since something else might implement IBase and be used for TGeneric.

juharr
  • 31,741
  • 4
  • 58
  • 93
1

In summary, you cannot cast ClassX to any class that implement IBase. You are only guaranteed to be able to cast it to IBase itself. Consider this example:

Imagine that you have a class ClassA that implements IBase like this:

public class ClassA : IBase
{

}

Now, ClassZ<ClassA> would look like this (this is not real code):

public class ClassZ<ClassA>
{
    Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right

    Func<ClassA> funcGeneric = ClassY.FunctionReturnX; //Wrong
}

ClassY.FunctionReturnX returns ClassX which you can cast to IBase, but you cannot cast it to ClassA. Therefore, you get the complication error.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62