Scott Nimrod
Scott Nimrod

Reputation: 11570

How do I implement a method with a variable number of arguments?

How do I implement a method with a variable number of arguments?

In C#, we can use the params keyword:

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
 }

So how can I do this in F#?

type MyClass() =

    member this.SomeMethod(params (args:string array)) = ()

I receive the following error from the code above:

The pattern discriminator 'params' is not defined

Upvotes: 3

Views: 393

Answers (1)

Lee
Lee

Reputation: 144206

You can use ParamArrayAttribute:

type MyClass() =
    member this.SomeMethod([<ParamArray>] (args:string array)) = Array.iter (printfn "%s") args

then:

let mc = MyClass()
mc.SomeMethod("a", "b", "c")

Upvotes: 10

Related Questions