Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Get instance that's calling the current method

Get instance that's calling the current method

Scheduled Pinned Locked Moved C#
question
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    partyganger
    wrote on last edited by
    #1

    Is it possible to get a reference to the object that is calling a method (maybe through something like Reflection)? i.e. something like: public class A { private B b; public A() { b.SomeMethod() } } public class B { public void SomeMethod() { if(callingInstance.Type == typeof(A) //do domething } }

    H 1 Reply Last reply
    0
    • P partyganger

      Is it possible to get a reference to the object that is calling a method (maybe through something like Reflection)? i.e. something like: public class A { private B b; public A() { b.SomeMethod() } } public class B { public void SomeMethod() { if(callingInstance.Type == typeof(A) //do domething } }

      H Offline
      H Offline
      Heath Stewart
      wrote on last edited by
      #2

      You can get the calling assembly using Assembly.GetCallingAssembly, but not the calling type. Since this is an object-oriented development platform, a more appropriate implementation would accept the caller as a parameter to the method, typically declared as an abstract class or an interface. The caller would have to implement that interface or extend that abstract base class and override whatever members are appropriate to call, so that your method or class can call those methods without knowing about a specific implementation of those methods.

      Microsoft MVP, Visual C# My Articles

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups