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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With