Graham February 2016

How to Cast A Variable Using Generic Type Parameter and 'as' Operator

I have the following generic static class which is being used in a Fluent API. It takes an input parameter and returns a wrapper class containing the parameter cast to the generic type.:

public static Foo<TOut> InputAs<TOut>(object parameter) {

    var castParameter = parameter as TOut;

    if(castParameter == null) {
         throw new Exception("Invalid cast");
    }

    return new Foo<TOut>(castParameter);

}

The problem is that the castParameter == null check always returns null. What would be the correct way to cast the object using the TOut generic parameter as the new type?

Answers


Luaan February 2016

Well, if parameter as TOut returns null, then the runtime type of parameter isn't TOut.

Don't forget that operator resolution is done at compile-time, so if you have cast operators defined, they will not be invoked here. If you do need that, you can use dynamic:

public static Foo<TOut> InputAs<TOut>(dynamic parameter) 
{    
    return new Foo<TOut>((TOut)parameter);
}

This will allow runtime operator resolution, and will call your cast operator if one is available. For example, it will allow you to pass long, while expecting int.

However, you probably want to find a different way of what you're trying to do; dynamic can be very useful, but it can also make debugging quite a bit harder, and you lose almost all compile-time warnings and errors that can help you identify problems before they happen.

Post Status

Asked in February 2016
Viewed 1,939 times
Voted 5
Answered 1 times

Search




Leave an answer