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);


About Rajan
I am Rajan Garg working as a Senior Software Engineer in a company. I am working on the Microsoft technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: