views:

463

answers:

5

Let's say we have these two classes:

public class Base
{
    public static int GetInt() { return 1; }
}

public class Derived : Base
{

}

Let's also say that a piece of code calls Derived.GetInt(). How can I tell from within GetInt() that it was Derived.GetInt() and not Base.GetInt() that was called? What reflection technique do I use?

A: 

There's no way to tell the difference, with Reflection or otherwise. The calls are precisely equivalent, and when compiling, already at MSIL level there is no difference.

Pavel Minaev
A: 

I don't think you do, since there is no Derived.GetInt. GetInt is a static member, and although you're referencing it through Derived, it only belongs to Base.

John Saunders
A: 

Since the method GetInt is a static method, and not an instance method, it will always be called from the base class. You can't truly call it from the derived class, because you aren't calling it from an instance.

Kibbee
A: 

You can do this if you want to have different functionality based on the class that the method is called through.

void Main()
{
   Console.WriteLine( Base.GetInt() ); // 1
   Console.WriteLine( Derived.GetInt() );  // 2
}

public class Base
{
 public static int GetInt() 
 { 
   return 1; 
 }
}

public class Derived : Base
{
  public static int GetInt()
  {
    return 2;
  }
}
JP Alioto
A: 

It's probably best to think of static methods simply as global functions. The class name serves as an extended namespace.