public class clsA<T, T1>
where T : class
where T1 : class
{
public T GetEntity()
{
return (T) new clsB<T1>();
}
}
I am getting error Cannot convert type
clsB<T1>to T
Please help
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
That’s because
Tcould be anything —stringfor example, and that would cause the cast to fail. IfTcannot be a variable type, then do not include it in the generic argument list.If you want to allow
Tto beclsB<T1>or any subtype, and you want to construct an instance of that class, then do this instead:Then, given the type:
Invoking
GetEntity()on an object of typeclsA<clsC, string>will construct and return an instance ofclsC.