Reputation: 22597
I have some code in method C that will get executed based upon the who called it.
public void C()
{
if(A called me) { .... }
if(B called me) { .... }
}
One way is to use a flag variable. Set the variable before calling C and then inside C process the flag.
Any other ideas?
Upvotes: 1
Views: 368
Reputation: 205
you could send a parameter to indentify which calles c, like 0 for A and 1 for B but i guess this counts as bad programming ...
Upvotes: 0
Reputation: 451
The following code could be used to retrieve the las calling method:
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
Upvotes: 2
Reputation: 1053
If this is C programming, I can achieve it by using function pointers technique provided that A and B have the same arguments. A and B will pass an identification information in one of the arguments for C to know who is calling... sort of WndProc() design in Win32 API where the message is the id and params are the data.
In C#, I think you can use delegates.
Upvotes: 0
Reputation: 62021
I think you can use Reflection to find this out if you really want to (I haven't done it), but it's a bad idea to use that in production code. Setting the flag, as you said, is a much better idea. In fact, the flag should have a semantic meaning, rather than "who called me". Finding out the caller method is most useful for logging and other diagnostic purposes.
Edit: Tried out the Reflection approach I was thinking of (calling System.Reflection.RuntimeMethodInfo.InternalGetCurrentMethod()
) and it doesn't work. :(
Upvotes: 1
Reputation: 29519
I would do this:
enum Funcs {A, B};
C(Func.A);
..
C(Func.B);
public void C(Funcs f)
{
if(f == Funcs.A) { .... }
if(f == Funcs.B) { .... }
}
Upvotes: 1
Reputation: 136653
Code smell.
Why does C care about the caller ? If the code in a method is different based on who called it, maybe you need different methods
A() calls A_C()
B() calls B_C()
e.g. If class Baker supports Bake(cakeSpec), it should behave identically no matter if it is called by CustomerA or CustomerB. You may want to customize some aspects of the baking, via some configuration params in cakeSpec. However on the whole, Bake() should do what it says.
Need more info.. as to exactly what you're trying to achieve.
Upvotes: 12