Regardless of whether or not this is a good idea, is it possible to implement an interface where the executing function is aware of the calling object’s type?
class A { private C; public int doC(int input) { return C.DoSomething(input); } } class B { private C; public int doC(int input) { return C.DoSomething(input); } } class C { public int DoSomething(int input) { if(GetType(CallingObject) == A) { return input + 1; } else if(GetType(CallingObject) == B) { return input + 2; } else { return input + 3; } } }
It seems to me like this is a bad coding practice (because the parameters don’t change, but the output would) but aside from that is it possible?
I’m in a situation were I want a few specific types to be able to call a certain function, but I can’t exclude access to the function. I thought about having a ‘type’ parameter
DoSomething(int input, Type callingobject)
But there’s no guarantee that the calling object would use GetType(this), as opposed to GetType(B) to spoof a B regardless of their own type.
Would this be as simple (relatively simple) as examining the callstack?
First, yes, it’s a terrible idea to do this and breaks all kinds of solid design principles. You should definitely consider an alternative approach if that’s open, like simply using polymorphism—this seems like it can be refactored to a pretty clear case of single dispatch.
Secondly, yes, it’s possible. Use
System.Diagnostics.StackTraceto walk the stack; then get the appropriateStackFrameone level up. Then determine which method was the caller by usingGetMethod()on thatStackFrame. Note that building a stack trace is a potentially expensive operation, and it’s possible for callers of your method to obscure where things are really coming from.Edit: This comment from the OP makes it pretty clear that this could probably be a generic or polymorphic method. @devinb, you might want to consider making a new question that provides more detail about what you’re trying to do, and we can see if it lends itself well to a good solution.