Home > Software engineering >  Passing a name of named optional argument to a method in C#
Passing a name of named optional argument to a method in C#

Time:10-23

I was wondering if I can do something like this, that is, pass a name of a named optional parameter to use it in a method call. I'm using a method from a library, which has like 50 optional named parameters (they only change a value of a permission, not really important for the context).

Is there a way to pass a parameter name? I wouldn't have to copy paste pretty much the same method just with a different parameter used at the end just to change a different permission

void Main()
{
  Test("first", "Hello");
  Test("third", "World");
}

void Test(string option, string value)
{
  // Do something
  TestHelper(option:value);
}

void TestHelper(string? first = null, string? second = null, string? third = null)
{
  // Do something
  return;
}

Thanks for any replies :)

CodePudding user response:

Assuming that the "option" names are passed "dynamically" you can use some reflection (cause otherwise there is not much sense in Test method cause TestHelper(first: "Hello") just works and is better/safe option):

class Helper
{
    public void Test(string option, string value)
    {
        var methodInfo = typeof(Helper).GetMethod(nameof(TestHelper));
        var parameterInfos = methodInfo.GetParameters();
        // todo - add runtime error for the case of invalid parameter name passed.
        methodInfo.Invoke(this, parameterInfos.Select(p => p.Name == option ? value : null).ToArray());
    }

    public void TestHelper(string? first = null, string? second = null, string? third = null)
    {
        // Do something
        return;
    }
}

Note that in general case reflection is quite costly so if the method is called quite often during the application lifetime you should consider "caching" it for example by using expression trees or just generating the method body using source generators.

  • Related