C # and a variable number of parameters

I tried the following code:

class Program: ProgParent
    {

        public int Max(params int[] op)
        {
            return 0;
        }

        public int Max(int i, params int[] op)
        {
            return 1;
        }

        public int Max(int i, int j, params int[] op)
        {
            return 2;
        }

        public static void Main(string[] args)
        {
            System.Console.WriteLine((new Program()).Max(5, 6, 7, 8));
            System.Console.ReadKey();
        }
    }

It performs and uses the most specific function. But the compiler does not give any warnings or errors about this. Why?

+3
source share
2 answers

The C # language specification says:

When performing overload resolution, a method with an array of parameters may be applicable either in its normal form [i.e. array transfer] or its extended form [ie passing a variable number of parameters]. the extended form of the method is available only if the normal form of the method is not available, and only if the method with the same signature as the extended form is not yet declared in the same type "

( ) : , .

, ( , ) :

  • : void fn (params object [] p), " " ( []). .
  • , , 1,2,3 , , . (, String.Format)
+4

( ) - ? ...

, - , , .

params , string.Concat .. ( + ).

+2

Source: https://habr.com/ru/post/1705625/


All Articles