locked
how to create named and optional parameters ? RRS feed

  • Question

  • User-1682137340 posted

    hi i created  named and optional parameters, but its getting errors ,

     can anyone solve it please

    class named_and_optnl_parameters
        {
            public static void raju(int i,int j)
            {
                Console.WriteLine(i+j);
            }
            public static void Main(string[] args)
            {
                raju(1,1);
                raju(k: 1 , l: 2);
    
            }
        }

    here is compile time errors occurs, they are      ; expected        invalid term         like that

    and also can't accepting default parameters.

    raju(k: 1 , l: 2);

     thanks in advance

    Sunday, September 14, 2014 1:47 PM

Answers

  • User753101303 posted

    Hi,

    See  http://msdn.microsoft.com/en-us/library/dd264739.aspx for details.

    In short for optional parameters you have to provide a default value and for named parameters you have of course to use the parameter names found in the method signature.

            public static void raju(int i,int j=5)
            {
                Console.WriteLine("i is {0} and j is {1}",i,j);
            }
            static void Main(string[] args)
            {
                raju(12);
                raju(j: 10, i: 5);
                Console.ReadKey();
            }
    

    Edit: on which line is your error? I would have expected a more explicit error. You may have some other error or could it be that you are using an old compiler that doesn't support this? For now the error seems unrelated to using named arguments...

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 14, 2014 2:23 PM