Search code examples
c#oopinheritancestatic-methodsstatic-classes

List of static classes in C#


I would like to have some classes, that all extend one base abstract class.

Then, I would like to have objects that each stores a subset of those classes and invokes the method they implement.

So I thought - I do nothing with the objects I store, so let's just make those classes static and I will not waste memory on storing object, just references to static classes, so I can invoke the static function. Question is - how do i do that?

For those who prefer code, here is what I need:

public static abstract class A {
    public static abstract void F();
}

public static class B : A {
    public static override void F() {
        ...
    }
}
// Class Storage of course does NOT work, its just here to illustrate what I need
public class Storage {
    private List<A> list;
    public void AddElement(A element) {
        list.Add(element);
    }
    public void DoStuff() {
        foreach(A element in list)
            element::F();
    }
}

Is there any way to do something like that? Or a different solution to such problem?


Solution

  • No you can't do that. There are a number of problems with what you're trying to do:

    1. You cannot use static types as type arguments—e.g. List<A>.
    2. You cannot use static types as method parameters—e.g. AddElement(A element).
    3. You cannot make a static type abstract, since there's no way to inherit from it.
    4. You cannot make a static method abstract even in a non-static class, since it cannot be overridden.

    From how you've described the problem, I can see no need for static types or static methods here. Just create a simple abstract class and inherit from it:

    public abstract class A {
        public abstract void F();
    }
    
    
    public class B : A {
        public override void F() {
            ...
        }
    }
    
    public class Storage {
        private List<A> list;
        public void AddElement(A element) {
            list.Add(element);
        }
        public void DoStuff() {
            foreach(A element in list)
                element.F();
        }
    }
    

    Alternatively, you can create a List<Type> and use reflection to invoke static methods on those types. For example:

    public static class A {
        public static void F() { ... }
    }
    public static class B {
        public static void F() { ... }
    }
    
    List<Type> typeList = new List<Type> { typeof(A), typeof(B) };
    foreach(var type in typeList)
    {
        type.GetMethod("F").Invoke(null, null); 
    }
    

    But using reflection is going to be slower than using direct method calls, and you'll loose all type-safety with this method (unless you write the type-checks yourself).