-1

I started to work with Generics, but the following code does not compile:

private T Test<T>() where T : class {
    if (typeof(T) == typeof(MyClass))
        return new MyClass();
    return null;
}

The error message is "Cannot implicitly convert type 'MyClass' to 'T'", despite the if statement exactly checks that T is of type MyClass.

What am I doing wrong?

Stefan
  • 1

2 Answers2

2

You can do this:

    private T Test<T>() where T : class, new()
    {
        if (typeof(T) == typeof(MyClass))
            return new T();
        return null;
    }

...but there is nothing inherently "generic" about this, because you already know the type.

rfmodulator
  • 3,638
  • 3
  • 18
  • 22
  • Exactly, what is the point of this, If it is type specific? I see no value, just unnecessary complexity – Munzer Apr 05 '20 at 16:23
  • @Munzer I suppose it's a learning exercise, but that doesn't concern me. – rfmodulator Apr 05 '20 at 16:24
  • 1
    Thanks for the answer, I was missing the new() constraint. The code is obviously much more complex, I tried to limit the example to show the essence of the problem. – Stefan Apr 05 '20 at 16:33
0

Generics are about keeping the type checks at compile time, where they can do the most good.

The result of typeof() and the if only resolves at runtime. So even if it makes sense for us humans that it could only be that one case, the compiler can not be sure of it. Only if the comparison was something like if(true) or if(a == true), could the compiler correctly infer what will happen. It needs compile time constants and literals to be sure of anything.

Also the whole concept of putting type specific code there is anathema to the purpose of generics. Whatever problem you try to solve here, is likely a XY problem. So you should be going a few steps back and explain what the X is, so we can tell you what the proper alternative to this Y is.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Christopher
  • 9,634
  • 2
  • 17
  • 31