5

UPDATE: This isn't about getting it to compile. The question is, why does the C# compiler allow the cast when using an interface, but it can't figure out the type when I use a class that implements the same interface.

I am getting the following error:

Cannot convert type 'Amber.BLL.iWeb.Session.AppSession' to 'TService'   

Here is the code:

public override TService GetService<TService>() 
{
    if ( typeof( TService ) == typeof( IAppSession ) )
    {
        AppSession session = new AppSession();
        return (TService) session;
    }
    throw new Exception( String.Format( 
        "iWebFactoryProvider cannot create services of type '{0}'.", 
        typeof( TService ).Name ) );
}

As it so happens, the AppSession class implements the IAppSession interface. If I change the line of code that instantiates AppSession to use the interface, like this:

IAppSession session = new AppSession();

suddenly everything compiles fine. I also note that it compiles fine if I do this:

AppSession session = new AppSession();
return (TService) (IAppSession) session;

In case it matters, the GetService() is overriding a method whose signature is declared like this:

public virtual TService GetService<TService>() where TService : class

In short, I can't figure out what the rules should be here so I can know how to avoid this situation in the future. Why was the compiler happy to cast the interface, but not happy to cast the interface's implementing class?

I note that this question is asking about a similar issue, but the answer isn't detailed enough for me to understand how it applies to my situation.

4
  • possible duplicate of C# generic method, Cannot convert type
    – jrummell
    Feb 29, 2012 at 15:08
  • The issue is similar, but the question is not the same. My question is: Why can it figure out the type when I use an interface, but it cannot when I use a class that implements the said interface? Feb 29, 2012 at 15:12
  • Because the compiler said so? I'm also curious.
    – jrummell
    Feb 29, 2012 at 15:13
  • Yeah, exactly. I know I can make it work, but this is a rare case when I don't know why the compiler is giving me an error in one case but not another. I'd like to understand it to be able to avoid similar issues in the future. Feb 29, 2012 at 15:19

3 Answers 3

18

Why does the C# compiler allow the cast when using an interface, but it can't figure out the type when I use a class that implements the same interface?

Good question. Consider the following:

public interface I {}
public class D {} // Note that D does not even implement I!
public class E
{
    public static M<T>(T t)
    {
        D d1 = (D)t; // Illegal
        D d2 = (D)(object)t; // Legal
        D d3 = (D)(I)t; // Legal
    }    
}

Let's break your question up into three questions.

Why is the cast directly from T to D illegal?

Suppose it were legal. Then E.M<D>(new D()) would work just fine; we'd cast the T to D and in fact it is a D, so no problem.

Now suppose we create an entirely different assembly with:

class C 
{
    public static explicit operator D(C c) { whatever }
}

And you call E.M<C>(new C()) in that assembly.. What do you reasonably expect to happen? You have an object of type C, it is being cast to D, and there is an explicit conversion operator right there from C to D. Most people would reasonably expect that the explicit conversion operator would be called.

But how on earth is the compiler supposed to realize when compiling the body of M that someone in the future might create a class C in a completely different assembly? The compiler has no way to emit the call to the conversion operator when compiling M. So we have three choices:

  1. Make cast operators sometimes use explicit conversion operators and sometimes not, depending on whether you're in a generic or not.
  2. Make cast operators start the compiler again at runtime to look for explicit conversion operators that might have been added in different assemblies after the original code was compiled.
  3. Disallow the cast in the first place.

In short, our choices are (1) make generics inconsistent, (2) make generics slow and unpredictable, or (3) disallow a feature that is already working against genericity. This is an easy choice to make; we chose (3).

If you want (2), you can have it in C# 4; dynamic starts the compiler again at runtime and works out whether there is an explicit conversion operator.

Why is the cast indirectly from T to D via object legal?

Because now no user-defined conversion can be relevant; there is never a user-defined conversion from object to anything.

Why is the cast indirectly from T to D via I legal?

Because now no user-defined conversion can be relevant; there is never a user-defined conversion from an interface to anything.

Bonus question:

But D does not even implement I! What's up with that?

A derived class of D might:

class F : D, I {}
...
E.M<D>(new F());

Now t can be cast to I because it might implement I, and I can be cast to D because it might be F.

If D were sealed then it would not be legal to cast from I to D because then there could not possibly be a derived F type.

8
  • Thank you, Eric. This is exactly the answer I was looking for. I wasn't taking user-defined conversions into consideration. That makes perfect sense now. Feb 29, 2012 at 17:14
  • 1+ Good description. So i've been not too wrong with my description of the problem, and the intention that it won't work because of IL-generation was right.
    – Felix K.
    Feb 29, 2012 at 18:58
  • It would seem this falls into the problem of using the same typecast syntax for both "I know this is really an X" and the "I know this isn't really an X" scenarios. The as operator seems to preclude the latter scenario, and casts with it are permissible, but only if the destination type is either constrained to be a class type, or is a Nullable<T> for a T which must be constrained to be a struct type. Would the CLR have any trouble with a construct that said, effectively, "if T is ___ {code where T is constrained} else {code to run if it can't be)"?
    – supercat
    Feb 29, 2012 at 21:23
  • @supercat: Indeed you have put your finger on it; a cast means two different things. As for your follow-up question: I suspect that in practice the verifier would have difficulty with such a method body, but I don't see any theoretical problem that would prevent improving the verifier if we wanted to do so. Feb 29, 2012 at 21:28
  • 2
    @supercat: We on the C# team have done a fair amount of testing on performance of generic types, particularly weird situations like generics with hundreds of type parameters, generics with deeply recursive structures, and so on. We haven't run into any notable problems. Feb 29, 2012 at 23:22
2

Have you tried adding a constraint for IAppSession?

public virtual TService GetService<TService>() where TService : IAppSession, class

That linked question is exactly the same issue. The compiler doesn't know that TService can be an AppSession.

3
  • I could do that. But I'm more interested in figuring out why the compliler accepts converting IAppSession to TService when it won't accept an object that implements the IAppSession interface. Feb 29, 2012 at 15:06
  • By the way, if you add a constraint for IAppSession, you won't have to do any type checking in your method because any usage that uses an incompatible type will be a compiler time error.
    – jrummell
    Feb 29, 2012 at 15:11
  • The linked question is not the same issue. The linked question wants to figure out how to get their code to compile. My question is: Why does it compile when I cast an interface to a generic, but it doesn't compile when I cast a class that implements that interface instead? Feb 29, 2012 at 15:14
2

You can convert the object by using (TService)(Object)instance or use constraints on the generic parameter.

The reason why the compiler is happy about the cast, is simply that he doesn't know what is behind the instance of a interface so the cast may succeed. When casting from class to generic type T he doesn't know if the cast is valid and throws a error at compile time. Of course he could do this also after compile but there is a good reason for this, imagine...

return (TService)myinstance;

is exchanged by:

return (CustomService)myinstance;

and the myinstance variable is not compatible with the type CustomService.

But a cast from a interface to TService may succeed, or from Object to TService.

4
  • Indeed, when I do so, it works out great. But as I said to jrummell above, I am trying to figure out why the compiler lets me cast to a generic type when I'm using the IAppService interface, but it won't let me do it when I'm using an object that implements IAppService. Feb 29, 2012 at 15:08
  • @CharlieKilian Little better description, i hope this helps.
    – Felix K.
    Feb 29, 2012 at 15:13
  • So what you are saying is, it really doesn't know in either case, but if I supply an interface, it errs on the side of guessing that it might just work, whereas if I supply a class, it errs on the side of guessing that it won't work. So basically, it's arbitrary, and the rules just aren't the same for interfaces as they are for classes. Is that what you are saying? Feb 29, 2012 at 15:17
  • @CharlieKilian Yes i think this is correct, i don't know exactly why the generics work this way but this is the idea i have. Of course another reason could be that the other way would end up in a corrupted IL-code but i never tested it. Would be interesting what happens when you change the constrain to a specific interface.
    – Felix K.
    Feb 29, 2012 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.