Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermine Calling Object Type in C#
    primarykey
    data
    text
    <p>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?</p> <pre><code>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; } } } </code></pre> <p>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?</p> <p>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</p> <pre><code>DoSomething(int input, Type callingobject) </code></pre> <p>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.</p> <p>Would this be as simple (relatively simple) as examining the callstack?</p> <hr> <p><strong>EDIT</strong> </p> <p>Please vote up JaredPar's answer (if you want) as well as John Feminella's. I could not mark both answers as accepted, and I accepted John Feminella's answer because it is specifically what I asked for, as opposed to Jared's answer which brought up a solution which I had not previously considered. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload