Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return specific type in generic method

Tags:

c#

generics

I have written the following method:

public T CreatePackage<T>() where T : new()
{
        var package = new T();

        if (typeof(ComponentInformationPackage) == typeof(T))
        {
            var compInfoPackage = package as ComponentInformationPackage;

            // ...

            return compInfoPackage;
        }

        throw new System.NotImplementedException();
}

I check what type T is and according to this I treat my variable Package. When I want to return it I get an compiler error.

"The type ComponentInformationPackage cannot be implicitly converted to T"

How can I solve this problem?

like image 930
user32323 Avatar asked Jan 27 '16 09:01

user32323


1 Answers

First: Where a cast doesn't work, a safe cast does work:

return CompInfoPackage as T;

...provided there's a class constraint on T:

public static T CreatePackage<T>() where T : class, new() { ... }

Second: Given this code:

var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
    var compInfoPackage = package as ComponentInformationPackage;

    // ...

    return (T)compInfoPackage; 
}

...you already have the reference package to the new object. Since it's of type T, the compiler already likes it as a return type. Why not return that?

var package = new T();
if (typeof(ComponentInformationPackage) == typeof(T))
{
    var compInfoPackage = package as ComponentInformationPackage;

    // ...

    return package; // Same object as compInfoPackage
}
like image 121
Petter Hesselberg Avatar answered Sep 17 '22 16:09

Petter Hesselberg