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

I thought I could use the new C # 6 operator name to create a key / value dictionary implicitly from the params array.

As an example, consider the following method call:

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

I'm not sure that there will be a test implementation that will be able to specify the name of the elements from the params array.

Is there a way to do this using only 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}"); } } 
+5
source share
1 answer

No, It is Immpossible. You do not have knowledge of the variable names used. Such information is not transmitted to the called party.

You can achieve what you want:

 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 the 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 might be to use Expression , which you pass to the method. There you can extract the variable name from the expression and execute the expression for its value.

+3
source

Source: https://habr.com/ru/post/1259224/


All Articles