views:

61

answers:

6

Hi, I have a parent class (Foo) with shared methods. It is MustInherit. Bar and Baz classes inherits from Foo. I will do something like that:

Dim baz as New Baz()
Dim bar as New Bar()

baz.sharedMethod()
bar.sharedMethod()

Within of Foo's sharedMethod(), I need to know who (class name) called it. So, using the above example, it would be, respectively, Baz and Bar.

Did you understand? Sorry about my english and thank you.

A: 

Within your function you could use:

Me.GetType().Name

This is assuming that your method is not declared as

Private/Public/Protected Shared MyMethod()

And that when you say "sharedmethod" you only mean that both classes have access to the method. If you have an actual Shared method, then you would need to use something from Reflection and Diagnostics to grab this information as described here.

Joel Etherton
A: 

Why do you need to know this? It doesn't seem like 'the right way' to go about things. If you need the shared method to do something special with its caller then have a Foo as a parameter to the shared method (at which point it's probably not worth it being shared any more!).

Will A
+2  A: 

That's not possible, you don't have the Me variable to know the type of the class. To avoid creating the illusion that it might be possible, you should write it like this:

 Foo.sharedMethod()
Hans Passant
A: 

You could give a parameter to the sharedmethod and indicate that way.

Shawn
I figured it but i wanna avoid that...
afe
Any reason why?
Shawn
A: 

You should probably think about overriding the method in child classes instead of using shared methods. In the override make sure to call the base class method. If there is functionality inside of the parent method that needs to know what called it (and cannot be moved to the child classes) then you should consider using generics. Then inside of the child class you would pass the child type into the constructor of foo.

Tony Abrams
A: 

There is probably a better design that you should consider instead. However, if you really want to know what class called a method, you can use System.Diagnostics.StackTrace to do this:

new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().DeclaringType
Jon B
This tends to fall apart in the Release build when the JIT compiler inlines the method. Or if it is called from a static method or an instance method from a base class. Also very expensive.
Hans Passant