I'm trying to create this generic method to simplify things but I think I messed it up! Can you help with my problem?
This compiles:
private string ConcatenateText<T1, T2>(MyEntity myEntity)
where T1 : Supplier, new()
where T1 : Employee, new()
where T2 : SupplierDepartment, new()
where T2 : EmployeeDepartment, new()
{
T1 p = new T1();
T2 r = new T2();
//Code here for myEntity treatment
return mystring;
}
While this does not compile:
protected void mybutton1_Click(object sender, EventArgs e)
{
string mystring = ConcatenaText<Supplier, SupplierDepartment>(myEntity);
}
//This does not compile
protected void mybutton2_Click(object sender, EventArgs e)
{
string mystring = ConcatenaText<Employee, EmployeeDepartment>(myEntity);
}
Message: The type Supplier cannot be used as type parameter T1 in the generic type or method ConcatenateText(MyEntity myEntity). There is no implicit reference conversion from Supplier to Employee
Can this be done? What am I doing wrong? Can it be improved?
EDIT:
And MyEntity is just another class in order to process it inside this generic method! It's not related to the types T. It just an argument. But it's clear that I can't do that, using 2 types like that. I thought that I could assign one or another and the CLR independently of my initialization could react as I wanted. I gonna accept the answer who share a little bit more information about it.
See Question&Answers more detail:os