4

I haven't been able to find the answer to this question through the typical channels.

In Python I could have the following function definition

def do_the_needful(**kwargs):
    # Kwargs is now a dictionary
    # i.e. do_the_needful(spam=42, snake='like eggs', spanish='inquisition')
    # would produce {'spam': 42, 'snake': 'like eggs', 'spanish': 'inquisition' }

I know .NET has the ParamArray, which produces a sequence of unnamed arguments, similar to the *args syntax in Python... Does .NET have an equivalent of **kwargs, or something similar?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290

1 Answers1

4

So, unfortunately, there is no way of simulating the Python **kwargs in C#. You will always loose parameter names in the process (see comment by @alelom below).

But, it seems that what you look for is a variadic function. If you want to know how to implement it in various programming languages, the best is to look at the Wikipedia page about it.

So, according to the Wikipedia, implementing a variadic function in C# and VisualBasic is done like this:

Other languages, such as C#, VB.net, and Java use a different approach—they just allow a variable number of arguments of the same (super)type to be passed to a variadic function. Inside the method they are simply collected in an array.

C# Example

public static void PrintSpaced(params Object[] objects)
{
    foreach (Object o in objects)
        Console.Write(o + " "); 
}    
// Can be used to print: PrintSpaced(1, 2, "three");

VB.Net example

Public Shared Sub PrintSpaced(ParamArray objects As Object())
    For Each o As Object In objects
        Console.Write(o & " ")
    Next
End Sub

' Can be used to print: PrintSpaced(1, 2, "three")

perror
  • 7,071
  • 16
  • 58
  • 85
  • 1
    C#/VB, and according to Wikipedia - nope, just the param only variety. – Wayne Werner Apr 25 '13 at 03:20
  • 13
    It's an equivalent of *args, not **kwargs. – Dmitriy Sintsov Nov 19 '16 at 09:28
  • Agree with @DmitriySintsov -- this answer is wrong, because `params` replicates the `*args` behaviour, not the `**kwargs` behaviour. You lose the parameter names with C#'s `params` keyword. From what I could gather, there is no built-in way to obtain the `**kwargs` behaviour in C# :( – alelom Jan 15 '23 at 08:41