Ali CAKIL
Ali CAKIL

Reputation: 428

how to get varriable name over another one c#?

string MyVar1 = "bilah bilah";
dosometing(MyVar1);

    void dosometing(object MyObject)
    {
       string VarName = nameof(MyObject);   // it givess : "MyObject"
    }

But I was expecting "MyVar1" is there a way for that? using dynamic? or ref?

Upvotes: 1

Views: 88

Answers (2)

Rand Random
Rand Random

Reputation: 7440

Maybe this information is usefull for you.

Since you want the value and the name of the property that has changed you could move the method dosomething inside the setter of the property.

(Notice: I am assuming you are actually working with properties and not local variables as shown in your question, and your question is just simplified)

So something like this:

public class Foo
{
    private string _myVar1;
    public string MyVar1
    {
        get => _myVar1;
        set
        {
            _myVar1 = value;
            DoSomething(value);
        }
    }


    private void DoSomething(string value, [CallerMemberName]string propertyName = "")
    {
         Console.WriteLine(value);
         Console.WriteLine(propertyName);
    }
}

The attribute CallerMemberName requires the using System.Runtime.CompilerServices

More Information can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute

See it in action here: https://dotnetfiddle.net/YvqqdP

Upvotes: 0

Jeethendra
Jeethendra

Reputation: 356

That's not possible. But you can do something like:

string MyVar1 = "bilah bilah";
dosometing(MyVar1, nameof(MyVar1));

void dosometing(string MyString, string VarName)
{
   // MyString holds the value
   // VarName holds the variable name
}

Upvotes: 4

Related Questions