Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get name of variables passed as `params object[]`?

Tags:

c#

.net

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?

like image 689
Markiian Benovskyi Avatar asked Oct 22 '25 10:10

Markiian Benovskyi


1 Answers

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"));
like image 193
Tim Schmelter Avatar answered Oct 25 '25 00:10

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!