How to return Type T in interface in C#?
c#, c#-4.0, generics, interface
Solution
public interface IUser<T> where T : User
{
//some properties here
T ToDerived(User u);
}
SalesUser : User, IUser<SalesUser>
{
//no properties needed because they exist in the User class
SalesUser ToDerived(User u)
{
//code for converting a base User to a derived SalesUser
}
}
Not sure this is what you want, but I added a generic type constraint on the interface to ensure that the generic type is `User` or inherits from it.
Problem
I have an interface like this: ``` public interface IUser{ //some properties here T ToDerived(User u); } ``` I'm new to interface development, so here's what I'm trying to accomplish. I will have a base class ``` public class User ``` that does NOT implement the above interface. Then I will have a derived class ``` SalesUser : User, IUser { //no properties needed because they exist in the User class SalesUser ToDerived(User u) { //code for converting a base User to a derived SalesUser } } ``` I would like to write the function for ToDerived(User u) in the SalesUser class, but in the interface, I do not know how to define this as the ToDerived method declaration that I have now in the interface is not compiling. I hope this makes sense.