Saturday, February 02, 2008

C# & Params Keyword

I ran into an interesting [at least to me :)] problem today.  How do I invoke all of the methods listed?

 

using System;

 

namespace ThinkFarAhead.Examples

{

    public class Params

    {

 

        public static void Main()

        {

            Max(1,2);

            //Max(1);  //Invokes #2?

            Max<int>(1,2);

            //Max<long>(1);  //Invokes #4?

        }

 

        //#1

        public static int Max(int first, params int [] values)

        {

            Console.WriteLine("[1] Param #2: {0}", values[0]);       

            return default(int);

        }

 

        //#2

        public static int Max(params int [] values)

        {

 

            Console.WriteLine("[2] Param #1: {0}", values[0]);

            return default(int);

        }

 

        //#3

        public static T Max<T>(T first, params T [] values)

        {

            Console.WriteLine("[3] Param #2: {0}", values[0]);       

            return default(T);

        }

 

        //#4

        public static T Max<T>(params T [] values)

        {

            Console.WriteLine("[4] Param #1: {0}", values[0]);       

            return default(T);

        }

 

 

    }

}

No comments: