Is there a C# alternative to Java's vararg parameters?

后端 未结 2 1528
轮回少年
轮回少年 2021-02-01 00:13

I have worked on Java and new to .Net technology

Is it possible to declare a function in C# which accepts variable input parameters

Is there any C# syntax simila

相关标签:
2条回答
  • 2021-02-01 00:35

    Have a look at params (C# Reference)

    The params keyword lets you specify a method parameter that takes a variable number of arguments.

    You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

    No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

    As shown in the example the method is declared as

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

    and used as

    UseParams(1, 2, 3, 4);
    
    0 讨论(0)
  • 2021-02-01 00:45

    Yes, C# has an equivalent of varargs parameters. They're called parameter arrays, and introduced with the params modifier:

    public void Foo(int x, params string[] values)
    

    Then call it with:

    Foo(10, "hello", "there");
    

    Just as with Java, it's only the last parameter which can vary like this. Note that (as with Java) a parameter of params object[] objects can easily cause confusion, as you need to remember whether a single argument of type object[] is meant to be wrapped again or not. Likewise for any nullable type, you need to remember whether a single argument of null will be treated as an array reference or a single array element. (I think the compiler only creates the array if it has to, but I tend to write code which avoids me having to remember that.)

    0 讨论(0)
提交回复
热议问题