C# 4 New Features – Named and Optional Parameters

C# 4 New Features – Named and Optional Parameters

Introduction

Microsoft introduced C# 4.0 with the Beta release of Visual Studio 2010. C# 4.0 has some new features as compared to the previous versions. In this post I will share the new feature introduced by Microsoft in C# 4.0 release is Named and Optional Parameters.

Why new features

Yes, that is the question? Why we need new features? Previous versions and advanced concepts are the answers to this question. Senior Programmers understand that if we need to write an overload methods, how much work is required and to maintain them is another issue which we deal after deployment of software.

Optional Parameters

The following example show the power of Optional Parameters, but we first see the old way to write the overload method:

public int Sum(int x, int y);
public int Sum(int x, int y, int z);
public int Sum(int x, int y, int z, int i);

How C# 4.0 accomplishes the above task

public int Sum(int x, int y, int z = 0, int i = 0);
Sum(5, 10); // 5 + 10 + 0 + 0
Sum(5, 10, 15); // 5 + 10 + 15 + 0
Sum(5, 10, 15, 20); // 5 + 10 + 15 + 20

Named Parameters

We add a method with name AddCustomer, sometimes we don’t need to pass the address or age then how we would neglect the values of address or age, let us see the example.

public void AddCustomer(string firstName, string lastName, string address = "NotAvailable", int age = 0);

In the above method address and age are optional method, but if we want to change the position of address of lastName then what should we do?

AddCustomer("Rais", address: "Pakistan", lastName: "Hussain");

Now if we don’t provide the address field, then we can call the AddCustomer method like that;

AddCustomer("Rais","Hussain", age: 28);

Conclusion

By the using of the above new features we can efficiently use Optional Parameters against overloaded method with the mixture of Named Parameters as per need.

C#

1 comment


  1. firma curatenie

    thanks for information. very useful :) )

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>