Yoav
Yoav

Reputation: 3386

Return List<this>

Is it possible to use this.GetType() as the type of a List?
I have the following class that is inherited by several objects:

public class MainRepository
{
    // ??? should be the type of this
    public List<???> GetAll()
    {
        return new List<???>();
    }
}

I know it can be done as a generic method like this:

    public List<T> GetAll<T>()
    {
        return new List<T>();
    }

But I wonder if it can be done without explicitly defining the type in the calling method.

Upvotes: 0

Views: 79

Answers (2)

Kjartan
Kjartan

Reputation: 19121

I believe you could do this, if that is a viable option for you?:

public class MainRepository<T>
{
    public List<T> GetAll()
    {
        return new List<T>();
    }
}

If I'm not mistaken, that should allow you to call the method without specifying the type in the method-call (though you obviously have to specify it for the class instead).

I'm assuming you want to do this in order to have some general generic repository, which can be sub-classed, or something similar? You could then do something like (just a rough idea):

public class BaseRepo {

}

public class MainRepository<T> : BaseRepo where T : BaseRepo{

    public List<T> GetAll(){
        return new List<T>();
    }
}

Upvotes: 1

Georg
Georg

Reputation: 5791

This is only possible through reflection since the true type of an object is only known at runtime. Therefore, you have to design your method to return the common base class of all lists, which is object in .NET, and create the list in the method dynamically.

public object GetAll()
{
    return System.Activator.CreateInstance(typeof(List<>).MakeGenericType(this.GetType()));
}

However, I do not see why you would want to do that.

Upvotes: 2

Related Questions