Search code examples
c#functionnamed-parameters

Can I pass arbitrary number of named parameters to function in C#?


Is there some kind of equivalent of Python's **kwargs in C#? I would like to be able to pass variable number of named arguments into functon, then get them as something Dictionary-like inside function and cycle over them.


Solution

  • There is nothing in C# available to let you pass in arbitrary named parameters like this.

    You can get close by adding a Dictionary<string, object> parameter, which lets you do something similar but requiring a constructor, the "parameter names" to be strings and some extra braces:

    static void Method(int normalParam, Dictionary<string, object> kwargs = null)
    {
       ...
    }
    
    Method(5, new Dictionary<String, object>{{ "One", 1 }, { "Two", 2 }});
    

    You can get closer by using the ObjectToDictionaryRegistry here, which lets you pass in an anonymous object which doesn't require you to name a dictionary type, pass the parameter names as strings or add quite so many braces:

    static void Method(int normalParam, object kwargs = null)
    {
        Dictionary<string, object> args = ObjectToDictionaryRegistry(kwargs);
        ...
    }
    
    Method(5, new { One = 1, Two = 2 });
    

    However, this involves dynamic code generation so will cost you in terms of performance.

    In terms of syntax, I doubt you'll ever be able to get rid of the `new { ... }' wrapper this requires.