3.2. C# Enhancements

C# 2010 introduces two useful features that have been present in VB for a long time: optional and named parameters (technically two separate features but often found together).

3.2.1. Named and Optional Parameters

Named parameters allow you to pass parameters into a function in any order and are near essential when using C#'s other new feature: optional parameters. 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 value 1 to a method's Copies parameter, COLOR to the ColorMode parameter, and readme.txt to DocumentName:

Print(Copies:1,ColorMode:"COLOR",DocumentName:"readme.txt");

static void Print(string ColorMode, string DocumentName, int Copies)
{...}

Optional parameters are created in C# by specifying a default value and must appear after required parameters:

static void Print(int Copies=1, string ColorMode="Color", string DocumentName="") {...}

This method can then be called in a multitude of ways, some of which are shown here:

Print(1);
Print(1, "Color");
Print(1, "Color", "My doc");
Print(Copies: 1);
Print(ColorMode: "Color");
Print(DocumentName: "myDoc.txt");
Print(Copies: 1, ColorMode: "Color");
Print(Copies: 1, ColorMode: "Color",  DocumentName: "myDoc.txt");

Optional parameters can make your code more readable and easier to maintain, and can reduce the amount of typing you have to do. They also can make it easier to work with COM objects (see the "Improved COM Interoperability" section). For example, if we are creating a Print() method that accepts a number of different parameters, we no longer have to overload it with a number of methods, as follows:

public void Print(string DocumentName)
{
    Print(DocumentName, 1, "COLOR");
}

public void Print(string DocumentName, int Copies)
{
    Print(DocumentName, Copies, "COLOR");
}
public void Print(string DocumentName, int Copies, string ColorMode)
{}

Optional parameters allow us to refine this as follows:

public void Print(string DocumentName, int Copies=1, string ColorMode="COLOR")
{...}

3.2.2. Rules (Nonoptional)

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

  • Nonoptional parameters must be declared first.

  • Nonoptional 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.204