Named and Optional Parameters

Named parameters allow you to pass parameters into a function in any order. To use a named parameter, simply specify the parameter name followed by a colon and then the value you are passing into a function. The following code illustrates passing the named parameter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpDemo
    class Program

        static void Main(string[] args)
            //Calling mehtod without named parameter
            AddNumbers(1, 2, 3);
            //Calling method with named parameter
            AddNumbers(c: 3, b: 2, a: 4,d:10);

        public static void AddNumbers(int a, int b, int c, int d = 0)
            int sum = a + b + c + d;
            Console.WriteLine("Sum={0}", sum);


There some rules you need to be aware of when working with named parameters.

  • Non-optional parameters must be declared first.
  • Non-optional parameters must still be specified when you call a method.
  • Parameters are evaluated in the order they are declared.
  • If two function signatures are equally valid for your input, then the one with no optional values is given precedence.

No comments:

Post a Comment