5

I have the below class structure. Class A is called from constructor of Class B and C.

Class A
{
    A()
}

Class B
{
    B()
    {
        A();
    }
}

Class C
{
    C()
    {
        A();
    }
}

Is there a way where I can get to know if the call to A() comes from B() or C()? I do not want to pass any object in the constructor.

vc 74
  • 37,131
  • 7
  • 73
  • 89
Rem San
  • 367
  • 1
  • 5
  • 20
  • Might be helpful : https://stackoverflow.com/a/1375429/6299857 – Prasad Telkikar Mar 20 '19 at 05:18
  • 2
    Not directly. It is probably bad practice to have the behaviour of A depend on the class that uses it - next time you want to use A from a totally different class you will get a surprise. It is best to pass in all inputs via parameters to the constructor, so that it is obvious how A works and so that it can be easily used by other classes (reusability!). – Erlkoenig Mar 20 '19 at 05:21

3 Answers3

6

This worked for me

var mth = new StackTrace().GetFrame(1).GetMethod();
var cls = mth.ReflectedType.Name;
Rem San
  • 367
  • 1
  • 5
  • 20
0

You can use CallerMemberNameAttribute to get caller name. Please check the following example from here. Hope this will help.

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output:
//  message: Something happened.
//  member name: DoProcessing
//  source file path: c:\Visual Studio Projects\CallerInfoCS\CallerInfoCS\Form1.cs
//  source line number: 31
Sampath
  • 1,173
  • 18
  • 29
-1

You need CallerMemberNameAttribute or CallerFilePathAttribute. Please refer to Microsoft's doc for more details https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information

public class FirstClass
{
     public string Run([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "")
    {
        return $"CallerMemberName is {memberName}. Calling from {sourceFilePath}";
    }
}

public class SecondClass
{
    public string CallFirstClass()
    {
        var firstClass = new FirstClass();
        return firstClass.Run();
    }
}

the output in the CallFirstClass() would be like this

CallerMemberName is CallFirstClass. Calling from D:\Development\WpfApp1\WpfApp1\SecondClass.cs
jedipi
  • 155
  • 4