0

I'm looking for way to get the type of inherited class from a static method of this class which is defined in the base class. I hope the code snippet makes it more clear.

Here is what I have tried, but this reflects the base type but not the child type:

abstract class Parent()
{    
    static Parent MyMethod()
    {   
        // I get the parent type but I want the child type         
        Type thisObjType = MehtodBase.GetCurrentMethod().DeclaringType;

        // Fails because I try to instantiate an abstract object
        Parent myChildObj = (Parent)Activator.CreateInstance(thisObjType);
        // ...

        return myChildObj;
    }
}


class Child : Parent
{        
}     

The call to this method failed because the delivered one is the parent type and not the child.

Child myChild = (Child)Child.MyMethod()

I've found this, but it's not the solution I'm looking for: Get derived class type from a base's class static method If possible, I would try to avoid the use of generic.

How do I get the type of the object from the static method? Thank you in advance!

fussel
  • 151
  • 1
  • 1
  • 10
  • 1
    I guess you know that the static methods are not inherited? how is `MyMethod` in any way related to Child ? – Selman Genç Sep 17 '18 at 09:14
  • 1
    Perhaps you should explain what your end goal is. – 500 - Internal Server Error Sep 17 '18 at 09:15
  • 1
    a static method is statically bound to a certain class and does not really participate in the inheritance-chain. Thus it does not exist in the derived class. The static method therefor does not know that it was actually used in the derived class. You can however - through a compiler-trick - access the static member from your derived class. – MakePeaceGreatAgain Sep 17 '18 at 09:20
  • @Selman: MyMethod I for shure not related to the object. But I hoped by using reflection it could know the class where it is called from. – fussel Sep 17 '18 at 10:03
  • @500- Internal Server Error: My goal is an class that behaves like double.Pares(someString) and returns a object based on the data it got from the string. But to me this was irrevelant for the question so I made a more abstract description. – fussel Sep 17 '18 at 10:12
  • @HimBromBeere: Of course, this is not the answer I was hoping for, but obviously it's not possible to do that the way I wanted to. Thanks for the clarification. – fussel Sep 17 '18 at 10:14

0 Answers0