George Mauer
George Mauer

Reputation: 122072

Is it possible to detect type when a static is called on a derived type

Given

public class Original {
  public static DoStuff() {
  }
}

public class Derived : Original {
}

when calling

Derived.DoStuff();

Weirdness of the requirement aside, is it possible within DoStuff() to detect the class that it was called on?

i.e. is it possible within the implementation of DoStuff() to tell the difference between Original.DoStuff(); and Derived.DoStuff();

Upvotes: 3

Views: 81

Answers (3)

Israel Lot
Israel Lot

Reputation: 653

As Jon said, not possible in C# because static methods have unique entry points. Anyway you are right, it's very weird that one would need to detect it.

Upvotes: 0

Attila
Attila

Reputation: 28762

Unless Derived provides its own definition of DoStuff, Derived.DoStuff() is equivalent to Original.DoStuff(). Static methods/member variables are associated with the class, not with any of the instances (objects).

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

Not in C#, no - the compiled IL refers directly to Original.DoStuff.

(I've just verified that VB apparently does the same thing for static calls, whereas IIRC there's a difference between VB and C# in the generated code when calling a virtual method via a "child" reference.)

Upvotes: 8

Related Questions