Search code examples
c#.netgenericsoperatorson-the-fly

Operator as and generic classes


I want to make a method:

object Execute()
{
    return type.InvokeMember(..);
}

to accept a generic parameter:

T Execute<T>()
{
    return Execute() as T;

    /* doesn't work:
    The type parameter 'T' cannot be used with the 'as' operator because
    it does not have a class type constraint nor a 'class' constraint */

    // also neither typeof(T), nor T.GetType() are possible

    return (T) Execute(); // ok
}

But I think operator as will be very useful: if result type isn't T method will return null, instead of an exception! Is it possible to do?


Solution

  • You need to add

    where T : class
    

    to your method declaration, e.g.

    T Execute<T>()  where T : class
    {
    

    By the way, as a suggestion, that generic wrapper doesn't really add much value. The caller can write:

    MyClass c = whatever.Execute() as MyClass;
    

    Or if they want to throw on fail:

    MyClass c = (MyClass)whatever.Execute();
    

    The generic wrapper method looks like this:

    MyClass c = whatever.Execute<MyClass>();
    

    All three versions have to specify exactly the same three entities, just in different orders, so none are any simpler or any more convenient, and yet the generic version hides what is happening, whereas the "raw" versions each make it clear whether there will be a throw or a null.

    (This may be irrelevant to you if your example is simplified from your actual code).