-1

When a field in an instance of a class belongs to another class, can the other class's instance knows the name of the class of which it is a field?

For example,

public class ClassA
{
    public void MethodA()
    {
        ... // can an ClassA instance know the name of the class of which   it is a field? 
    }
}

public class ClassB
{
    Public ClassA objA;
    public void MethodB()
    {
        objA.MethodA(); 
    }
}

public class ClassC
{
    Public ClassA objA;
    public void MethodC()
    {
        objA.MethodA();   
    }
}

public static void Main(string[] args)
{
    ClassB objB = new ClassB();
    objB.MethodB();

    ClassB objC = new ClassC();
    objC.MethodC();
}

When either objB.MethodB() or objC.MethodC() calls objA.MethodA(), inside objA.MethodA(), can it know the name of the class of which objA is a field, without having to pass the name of the class as a parameter to objA.MethodA()? Thanks.

Tim
  • 1
  • 141
  • 372
  • 590
  • I would think it is possible via a stack trace. But that is just asking for a whole lot of unnecessary work. IMHO – Nkosi Jun 10 '17 at 00:28
  • Thanks. Can you elaborate? – Tim Jun 10 '17 at 00:28
  • @Tim why not add an `object caller` argument to MethodA? StackTrace is super slow – Michal Ciechan Jun 10 '17 at 00:28
  • 2
    An arbitrary number of classes could potentially reference a single instance of `ClassA`, so it makes no sense in general to ask for the name of "the" referencing class. – Michael Liu Jun 10 '17 at 00:28
  • @Tim [How can I find the method that called the current method?](https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method) – Nkosi Jun 10 '17 at 00:29
  • 2
    Also take a look at [Caller*] attributes in https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices(v=vs.110).aspx – Michal Ciechan Jun 10 '17 at 00:30
  • Why not make B and C inherit A. Then you can use typeof(ClassB) or typeof(ClassC) to determine the type. – jdweng Jun 10 '17 at 00:58

1 Answers1

1

How about using an appropriate parameter and a tiny interface! Both Class C and class B can implement an interface ICallers. Acctually this interface is a marker.

 class C:ICaller
 {
   ...
 }
 class B :ICaller
 {
  ...
 }

Now the method inside the class A can take advantage of the parameter wich can help us to determine which class has called the method

 public void MethodA(ICaller caller)
 {
    var class = caller as B;
    if(class!=null)
    ...
 }

public class ClassC
{
    Public ClassA objA;
    public void MethodC()
    {
        objA.MethodA(this);   
    }
}
Mahmood Shahrokni
  • 226
  • 1
  • 3
  • 12