Optional and Named Parameters

Optional parameters allow us to provide default values for some of the parameters of methods and allow type of overloading. Here’s an example:

public void CreateUser(string firstName, string lastName, bool isAdmin, bool isTrialUser) {}

If we want to overload this method and have default values for the two bool parameters, then we could have easily few more methods. Now with optional parameters, we are able to do something like this:

public void CreateUser(string firstName, string lastName, bool isAdmin = false, bool isTrialUser = true) {}

In above code, the parameters firstName and lastName do not have default value set, while isAdmin and isTrialUser do have default value set. As a consumer of this method, i can do some of the following:

myClass.CreateUser(“Jessica”,”Alba”); //isAdmin and isTrailUser set to default value set

myClass.CreateUser(“Jessica”,”Alba”, true); //isAdmin set to true and isTrialUser to default

myClass.CreateUser(“Jessica”,”Alba”, true, false);

myClass.CreateUser(“Jessica”,”Alba”, isTrialUser: false); //isAdmin set to default and isTrialUser to false

The last example makes use of named parameters. This new feature make code easier to read and understand. Look at below lines of code:

File.Copy(@”c:\myFile.txt”, @”c:\myOtherFile.txt”, true);

File.Copy(sourceFileName: @”myFile.txt”, destFileName: @”c:\myOtherFile.txt”, overwrite: true);

%d bloggers like this: