Visual Studio .NET - Named and Optional Argument in C# 2010

Asked By aman on 11-Aug-11 02:58 AM
hi all,

what are named and optional Argument in C# 2010?
how named and optional Argument differ from each other?

Example on both Namd and Optional Argument...........

thanks and regards
Aman Khan
Cos mos replied to aman on 11-Aug-11 03:04 AM
class NamedExample
{
    static void Main(string[] args)
    {
      // The method can be called in the normal way, by using positional arguments.
      Console.WriteLine(CalculateBMI(123, 64));

      // Named arguments can be supplied for the parameters in either order.
      Console.WriteLine(CalculateBMI(weight: 123, height: 64));
      Console.WriteLine(CalculateBMI(height: 64, weight: 123));

      // Positional arguments cannot follow named arguments.
      // The following statement causes a compiler error.
      //Console.WriteLine(CalculateBMI(weight: 123, 64));

      // Named arguments can follow positional arguments.
      Console.WriteLine(CalculateBMI(123, height: 64));
    }

    static int CalculateBMI(int weight, int height)
    {
      return (weight * 703) / (height * height);
    }
}

namespace OptionalNamespace
{
    class OptionalExample
    {
      static void Main(string[] args)
      {
        // Instance anExample does not send an argument for the constructor's
        // optional parameter.
        ExampleClass anExample = new ExampleClass();
        anExample.ExampleMethod(1, "One", 1);
        anExample.ExampleMethod(2, "Two");
        anExample.ExampleMethod(3);

        // Instance anotherExample sends an argument for the constructor's
        // optional parameter.
        ExampleClass anotherExample = new ExampleClass("Provided name");
        anotherExample.ExampleMethod(1, "One", 1);
        anotherExample.ExampleMethod(2, "Two");
        anotherExample.ExampleMethod(3);

        // The following statements produce compiler errors.

        // An argument must be supplied for the first parameter, and it
        // must be an integer.
        //anExample.ExampleMethod("One", 1);
        //anExample.ExampleMethod();

        // You cannot leave a gap in the provided arguments.
        //anExample.ExampleMethod(3, ,4);
        //anExample.ExampleMethod(3, 4);

        // You can use a named parameter to make the previous
        // statement work.
        anExample.ExampleMethod(3, optionalint: 4);
      }
    }

    class ExampleClass
    {
      private string _name;

      // Because the parameter for the constructor, name, has a default
      // value assigned to it, it is optional.
      public ExampleClass(string name = "Default name")
      {
        _name = name;
      }

      // The first parameter, required, has no default value assigned
      // to it. Therefore, it is not optional. Both optionalstr and
      // optionalint have default values assigned to them. They are optional.
      public void ExampleMethod(int required, string optionalstr = "default string",
        int optionalint = 10)
      {
        Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr,
          optionalint);
      }
    }

    // The output from this example is the following:
    // Default name: 1, One, and 1.
    // Default name: 2, Two, and 10.
    // Default name: 3, default string, and 10.
    // Provided name: 1, One, and 1.
    // Provided name: 2, Two, and 10.
    // Provided name: 3, default string, and 10.
    // Default name: 3, default string, and 4.

}


Riley K replied to aman on 11-Aug-11 03:06 AM
Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

Parameters are optional when a default value is specified as part of a declaration.  For example, the method below takes two parameters – a “category” string parameter, and a “pageIndex” integer parameter.  The “pageIndex” parameter has a default value of 0, and as such is an optional parameter:

http://weblogs.asp.net/blogs/scottgu/image_30D9EE32.png

When calling the above method we can explicitly pass two parameters to it:

http://weblogs.asp.net/blogs/scottgu/image_36485ED6.png

Or we can omit passing the second optional parameter – in which case the default value of 0 will be passed:

http://weblogs.asp.net/blogs/scottgu/image_635D4BA4.png 

Note that VS 2010’s Intellisense indicates when a parameter is optional, as well as what its default value is when statement completion is displayed:

http://weblogs.asp.net/blogs/scottgu/image_147C8645.png



Named Arguments and Optional Parameters in C# 4.0

C# 4.0 also now supports the concept of “named arguments”.  This allows you to explicitly name an argument you are passing to a method – instead of just identifying it by argument position. 

For example, I could write the code below to explicitly identify the second argument passed to the GetProductsByCategory method by name (making its usage a little more explicit):

http://weblogs.asp.net/blogs/scottgu/image_60D419E6.png

Named arguments come in very useful when a method supports multiple optional parameters, and you want to specify which arguments you are passing.  For example, below we have a method DoSomething that takes two optional parameters:

http://weblogs.asp.net/blogs/scottgu/image_11F35487.png

We could use named arguments to call the above method in any of the below ways:

http://weblogs.asp.net/blogs/scottgu/image_7ED227DA.png

Because both parameters are optional, in cases where only one (or zero) parameters is specified then the default value for any non-specified arguments is passed.

dipa ahuja replied to aman on 11-Aug-11 03:17 AM

Named arguments: They free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. For example, a function that calculates body mass index (BMI) can be called in the standard way by sending arguments for weight and height by position, in the order defined by the function.




For ex:

class B
{
  Public void getName(string name)
  {
    
  }
}

In this method it takes 1 argument that is string and you must pass the argument to call this method 


Optional Argument : The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.


class B
{
  Public void getCountry(string Country="India")
  {
    
  }
}
Here to call this method you have to pass a string variable, 
But as you can see it is assigne a value India, That means this is optional argument.
It means if you pass any string then it will take that string 
But if u dont pass then the country variable will contain India 

For Ex:

B b1 = new B();

b1.getCountry("Canada"); //take country as Canada
b1.getCountry(); //Take country as Default value that is india

Anoop S replied to aman on 11-Aug-11 03:31 AM
Named and optional parameters are really two distinct features, and allow us to either omit parameters which have a defined default value, and/or to pass parameters by name rather than position. Named parameters are passed by name instead of relying on its position in the parameter list, whereas optional parameters allow us to omit arguments to members without having to define a specific overload matching.

Let’s have a look at Optional parameters:

//In old way we will write the code as shown below.
public static double MyOldCurrencyExchange(double amount, double rate) 
{ 
    return (amount * rate); 
}

We will call the above method as shown below:

MyOldCurrencyExchange(500, 1.18);

Now, by using Optional parameters:

//In new way we will write the code as shown below
public static double MyNewCurrencyExchange(double amount, double rate=1) 
{ 
    return (amount * rate); 
}

We will call the above method as shown below:

MyNewCurrencyExchange (500, 1.18);  // ordinary call 
MyNewCurrencyExchange (500);  // omitting rate

Now, by using Named parameters:

MyNewCurrencyExchange (rate:1.18, amount:500); // reversing the order of arguments.

Now, by using Named and Optional parameters:

MyNewCurrencyExchange (amount:500);
Jitendra Faye replied to aman on 11-Aug-11 04:43 AM

Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods.

 The parameter for each argument can be specified by parameter name. For example, a function that calculates body mass index (BMI) can be called in the standard way by sending arguments for weight and height by position, in the order defined by the function.

CalculateBMI(123, 64);

If you do not remember the order of the parameters but you do know their names, you can send the arguments in either order, weight first or height first.


CalculateBMI(weight: 123, height: 64);

CalculateBMI(height: 64, weight: 123);

Named arguments also improve the readability of your code by identifying what each argument represents.


Optional parameters are defined at the end of the parameter list, after any required parameters.

If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.

For more detail follow this link-
http://msdn.microsoft.com/en-us/library/dd264739.aspx
Hope this will help you.