lundi 18 mars 2019

Get the original name of a variable passed as a parameter?

Obviously, I can use the nameof operator to get the name of a variable or a parameter. But is there a way I can get the original name of a variable that's passed to a method? Currently, I have to do it like this:

static void Foo(string someVariable, string variableName)
{
    if (!FulfilsCondition(someVariable))
        Console.WriteLine($"{variableName} is bad!");

    // More code
}

And I call it like this:

string bar = string.Empty;
Foo(bar, nameof(bar));    // Or...
//Foo(bar, "bar");

But I'm looking for a way to avoid repeatedly providing the name of the variable and, instead, use something like:

Foo(bar);

Where Foo, in this case, would be:

static void Foo(string someVariable)
{
    string variableName = GetOriginalVariableName(someVariable);
    //  Is this possible? ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ 
    if (!FulfilsCondition(someVariable))
        Console.WriteLine($"{variableName} is bad!");

    // More code
}

Is something like this achievable in .NET?





Aucun commentaire:

Enregistrer un commentaire