Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

nameof

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}");
    }
}
like image 742
Veverke Avatar asked Nov 03 '16 13:11

Veverke


1 Answers

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.

like image 194
Patrick Hofman Avatar answered Oct 19 '22 20:10

Patrick Hofman