bobbyalex
bobbyalex

Reputation: 2751

Returning generic types in c#

public class Manager<T> where T: IBallGame
{
T GetManager()
{
//if T is ISoccer return new Soccer()
//if T is IFootball return new Football()

//This wont work. Why?
if (typeof(T) == typeof(ISoccer))
                return new Soccer();
}
}

Interface ISoccer: IBallgame
{
}
class Soccer: ISoccer
{
}
Interface IFootball: IBallgame
{
}
class Football:IFootball
{
}

I have already checked out this question How do I make the return type of a method generic?. Is there something more elegant than Convert.ChangeType()?

Why is it not possible to return an instance of Soccer or Football when there is a constraint on the type?

Upvotes: 0

Views: 770

Answers (2)

Preston Guillot
Preston Guillot

Reputation: 6714

If you expect different implementations based on the exact type of the generic, you're not actually dealing with a generic any more.

You should define two classes, e.g. FootBallManager : Manager<IFootball> and SoccerManager : Manager<ISoccer>

Based on your update, what you actually want is an additonal constraint on your generic of new() and to implement your class as

public class Manager<T> where T: IBallGame, new()
{
    T GetManager()
    {
         return new T();         
    }
}

Upvotes: 5

Valentin Kuzub
Valentin Kuzub

Reputation: 12073

public class Manager<T> where T : class, IBallgame
{
    T GetManager()
    {
        //if T is ISoccer return new Soccer()
        //if T is IFootball return new Football()


        if (typeof(T) == typeof(ISoccer))
            return new Soccer() as T;

        //code
    }
}

public interface IBallgame
{

}
public interface ISoccer : IBallgame
{
}
public class Soccer : ISoccer
{
}
public interface IFootball : IBallgame
{
}
class Football : IFootball
{
}

You just need a class constraint and as T

Upvotes: 2

Related Questions