Search code examples
c#classstatic-methodsgettype

Is it possible to run a static method using getType function in C#?


I have a base class and some derived classes that have some static methods. Is it possible to run static method if I know only the object of base class.

Ive tried typeof and getType methods to do it but as I realised they give only the Type. I know that my issue can be solved by comparing Type with my classes and finally it will work fine. But I hope that better pattern exists.

Type type = building.GetType();
type.arrangeCeremony(); // arrange ceremony is public static method in all derived classes

Thanks for your answers


Solution

  • If the operation depends on the type: the most reasonable way to implement that is simply: polymorphism.

    So: make the method non-static and move it to a base-type, as either virtual or abstract, and then override it in the sub-types. Then you don't need to ask the building what type it is: you just use polymorphism

    building.ArrangeCeremony();
    
    abstract class SomeBase {
        public abstract void ArrangeCeremony();
    }
    class SomeConcrete : SomeBase {
        public override void ArrangeCeremony() { /* code here */ }
    }
    

    If not all types can sensibly implement the method, then perhaps create an interface, or have the method declared at some sensible intermediate type level, and use a type test:

    if (building is ICeremonial ceremonial)
    {
        ceremonial.ArrangeCeremony();
    }
    
    class SomeBase { }
    interface ICeremonial {
        void ArrangeCeremony();
    }
    class SomeConcrete : SomeBase, ICeremonial {
        public void ArrangeCeremony() { /* code here */ }
    }
    

    or

    if (building is Ceremonial ceremonial)
    {
        ceremonial.ArrangeCeremony();
    }
    
    class SomeBase { }
    abstract class Ceremonial : SomeBase {
        public abstract void ArrangeCeremony();
    }
    class SomeConcrete : Ceremonial {
        public override void ArrangeCeremony() { /* code here */ }
    }