Is it possible to imply the name of the parameters of a params array using the nameof operator?
Asked Answered
W

1

8

I thought I could make use of the new c# 6 operator nameof to build a dictionary of key/values implicitly from a params array.

As an example, consider the following method call:

string myName = "John", myAge = "33", myAddress = "Melbourne";
Test(myName, myAge, myAddress);

I am not sure there will be an implementation of Test that will be able to imply the name of the elements, from the params array.

Is there a way to do this using just nameof, without reflection ?

private static void Test(params string[] values)
{
    List<string> keyValueList = new List<string>();

    //for(int i = 0; i < values.Length; i++)
    foreach(var p in values)
    {
        //"Key" is always "p", obviously
        Console.WriteLine($"Key: {nameof(p)}, Value: {p}");
    }
}
Wiry answered 3/11, 2016 at 13:53 Comment(2)
nameof is a compiler time facility, not a runtime one.Lottery
There's no need for myName, myAge, etc. to exist in the compiled IL. If it doesn't exist, it can't be got.Delinda
R
4

No, that is not possible. You don't have any knowledge of the variables names used. Such information is not passed to the callee.

You could achieve what you want like this:

private static void Test(params string[][] values)
{
    ...
}

public static void Main(string[] args)
{
    string myName = "John", myAge = "33", myAddress = "Melbourne";
    Test(new string[] { nameof(myName), myName });
}

Or using a dictionary:

private static void Test(Dictionary<string, string> values)
{
    ...
}

public static void Main(string[] args)
{
    string myName = "John", myAge = "33", myAddress = "Melbourne";
    Test(new Dictionary<string, string> { { nameof(myName), myName }, { nameof(myAge), myAge} });
}

Or using dynamic:

private static void Test(dynamic values)
{
    var dict = ((IDictionary<string, object>)values);
}

public static void Main(string[] args)
{
    dynamic values = new ExpandoObject();
    values.A = "a";
    Test(values);
}

Another possibility would be the use of an Expression, which you pass in to the method. There you could extract the variable name from the expression and execute the expression for its value.

Rockrose answered 3/11, 2016 at 13:57 Comment(4)
I am using a dictionary, I just thought of creating an overload that was "smarter".Wiry
Okay, expressions may come in handy. But more as a last resort I think.Rockrose
If you want something "smarter" use and anonymous type and convert to a dictionary or a namevaluecollectionArmada
@MatthewWhited that's an option too. Couldn't get it working with an anonymous type (guess I was too lazy to write the reflection for it), but dynamic will do.Rockrose

© 2022 - 2024 — McMap. All rights reserved.