Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods from abstract class

Tags:

c#

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?

like image 209
B Slater Avatar asked Mar 26 '26 04:03

B Slater


1 Answers

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.

like image 191
Ivan R. Avatar answered Mar 28 '26 17:03

Ivan R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!