thrashead
thrashead

Reputation: 337

How to Know Static Methods's Class Name

I have a class and it has some static methods. I have also another class inherits my first class like below;

public class Business
{
    public static DataTable Get()
    {
    }
}

public class Model : Business
{
    public int ID { get; set; }
    public string CompanyName { get; set; }
}

I use it like below;

Model.Get();

Inside of Do method i try to catch type of Model class. I can catch Business class type like below inside of Do method;

public static DataTable Get()
{    
    Type t = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
}

But i can't catch the Model class type. How can i do that?

Note : Get method in Business class selects columns up to which class it is called from. This is why i need name of Model class. Cause name of Model class will be name of table and it will select columns from table Model.

Note 2 : Normally i use it like;

Business.Get<Model>();

and i can get all data from Model table. But i try to use it like;

Model.Get();

Upvotes: 2

Views: 214

Answers (2)

pwas
pwas

Reputation: 3373

There is no method inheritance when it is going about static methods. Calling Do() method in B class is allowed only for convenience, I believe. I suppose that your call B.Do() is compiled to A.Do() (because B class doesn't contain Do() method declaration). That is why your snippet returns A.

In order to make your method return B you should write:

public class A
{
    public static void Do()
    {
    }
}

public class B : A
{
    public static void Do()
    {
    }
}

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

You can't. There is nothing called B.Do(). It implicitly means that A.Do().

Do is a static method defined in A. There is no metadata of B exist in Do method as it's defined in A.

Being able to call B.Do(); is just a convenience that C# compiler provides you. Note that resharper will warn you for this usage of base class member using a derived type.

Do note that even if you write

B.Do();

Compiler converts it to

call A.Do// Call IL

Update: As for the updated question, I recommend you to use instance methods as opposed to static methods.

Model model = new Model();
model.Get();

Inside of get you can use GetType().Name to get the class name of current instance.

public class Business
{
    public DataTable Get()
    {
         string className = this.GetType().Name;
    }
}

Upvotes: 5

Related Questions