B Slater
B Slater

Reputation: 340

Static methods from abstract class

I know similar questions have been asked often enough on here but I've been searching for a while for something that deals with the issue I'm having.

I'm building an application and had three separate classes for 'Team', 'Manager' and 'Employee'. I realised that I was repeating a lot of code for all three so I defined an abstract class called 'Worker'.

On each of the classes I've defined a GetAllX method that returns and IEnumerable<X>, for example:

public static IEnumerable<Manager> GetAllManagers()
{
    //Code to get all managers
    yield return m
    //find next manager and loop
}

What I want is to be able to define a method in my abstract class called GetAll which will return an IEnumerable of type T where T is the class inheriting from my abstract class. Is there any way to achieve something like this?

Upvotes: 4

Views: 3266

Answers (1)

Ivan R.
Ivan R.

Reputation: 1915

Technically you could do

abstract class Worker
{
    public static IEnumerable<T> GetAll<T>() where T : Worker
    {
        //your code
    }
}

class Manager : Worker
{
}

class Employee : Worker
{
}

And this method calling var managers = Worker.GetAll<Manager>();


Another approach using different static variables, what OP wants as described in comment.

abstract class Worker<T> where T : Worker<T>
{
    protected static string name;

    public static IEnumerable<T> GetAll() 
    {
        Console.WriteLine(name);
        return Enumerable.Empty<T>();
    }
}

class Manager : Worker<Manager>
{
    static Manager()
    {
        name = "Manager";
    }
}

class Employee : Worker<Employee>
{
    static Employee()
    {
        name = "Employee";
    }
}

And using

//create object to call static constructors
//this need only once for every concrete class
var test = new Manager();
var test1 = new Employee();

var managers = Worker<Manager>.GetAll();
var employees = Worker<Employee>.GetAll();

Technically, you can do it, but in my opinion, classical repository is approach that is more suitable.

Upvotes: 1

Related Questions