Reputation: 2161
I wonder, if it is possible to get the names of variables passed to method via params object[] values
?
The signature of method looks like this:
public static void ExecuteSafely(
Action callback,
string command,
params object[] values)
{
// code here
}
I was trying to get the values with nameof(values[index])
, but it tells me:
Expression does not have a name.
The point of this is to dynamically add parameters to SQL command, and it would be easier and less parameters to pass if I could add them based on the names of params, but the number of those params should be variable.
Can you recommend any solution or another approach to this?
Upvotes: 4
Views: 1906
Reputation: 460238
No, that's not possible. nameof
is a compile time feature and you want the name of variables at runtime(an array could be created dynamically).
If names are important for you use a Dictionary<string, object>
or with C#7 a named tuple:
public static void ExecuteSafely(Action callback, string command,
params (string name, object value)[] commandParameters)
{
foreach ((string Name, object Value) commandParameter in commandParameters)
{
string name = commandParameter.Name;
object value = commandParameter.Value;
// ...
}
}
Call it in this way:
ExecuteSafely(yourAction, "CreateUser", ("UserName", "Tim Schmelter"));
Upvotes: 10