0

Here is my problem: I have two classes which each include a method. Method 1 of class 1 calls method 2 of class 2. Now, I need to store in a local variable of method 2 (of type string probably), the name of the method that called method 2 (i.e. Method1).

For this I have set up a global variable named string str in class 2. However, as we create a new instance of class 2 when we call method 2, we have: str=null.

Here is the code so that you understand the problem:

public class Class1
    {
        private Class2 _class2 = new Class2();
        public Class2 Class2 { get => _class2; set => _class2 = value; }

        public void Method1()
        {
            Class2.data = "Changes I want to Make in Class2";
            Class2.Method2();
        }
    }
public class Class2
    {
        public string data;

        public void Method2()
        {
            string str = data; //str=null instead of str="Changes I want to Make in Class2"
            //Rest of the code here
        }
    }

I know that str=null since I instantiate the object Class2 = new Class2().

So, I need to find another way around the problem, and I realised that, in my case, getting the name of Method 1 from a local variable in Method 2 would be a solution.

My question is therefore the following: Is there a way to answer this problem?

Note: I am a beginner in computer development, so I apologise in advance if the solution is easy and I have not seen it before.

HugoG
  • 39
  • 3
  • 1
    Why not pass the name as parameter to Method2? – Klaus Gütter Mar 12 '21 at 15:17
  • 1
    In general, knowing the name of the calling method is a code-smell. It would be preferred if a value were passed-in instead. This makes the method testable and its behavior more opaque to callers. –  Mar 12 '21 at 15:18
  • 1
    I think I'm following your question. Take a look at this: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute. You can declare a parameter to `Method2` that will be automatically populated with the caller method name by doing `public void Method2(string [CallerMemberName] callerName = "")` (after a `using` reference to `System.Runtime.CompilerServices`). This is really handy if you are writing a logging system, for example. – Flydog57 Mar 12 '21 at 16:08
  • 2
    Note that the answers in the close notice (as posted by @Amy) are all somewhat outdated. The have you looking at the stack. If you can, using the more modern `System.Runtime.CompilerServices.CallerMemberNameAttribute` is a much better solution. One of the answers uses that attribute in an _Update_ to the original answer – Flydog57 Mar 12 '21 at 16:18

0 Answers0