Sunday, November 02, 2008

C# 4.0: Optional and Named Parameters - CTP Release

C# Chief Architect Anders Hejlsberg explained the future of C# in PDC2008.Initial CTP release of C# 4.0 has a feature of Optional and Named Parameters.

I have already explained the another featire of C# 4.0 is Dynamic Programming in my previous post.

Here I am going to explain about Named and Optional Parameters.

C# 1.0, 2.0, 3.0 doest not have a feature of Optional parameter. But in VB, we can define a method with an optional parameters.

Developers facing some difficulties of not having an optional parameter in C# especially when communicating with COM object.

C# 4.0 going to have a feature of Optional Parameter.

In previous version of C#, we have to implement multiple overloaded methods to have a variable parameters in the function like


C# 3.0:

public int Add(int x, int y)
{
return x + y;
}

public int Add(int x, int y, int z)
{
return x + y + z;
}

C# 4.0 (Optional Parameter):

public int Add(int x, int y, int z = 0)
{
return x + y + z;
}

//calling
Add(1,2);
Add(1,2,3


Here we can declare the parameter as an optional by initializing the value to the variable.

if we have multiple optional parameter in a function, we have to initialize the value sequentially in VB like

VB:


Public Function Add(ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Integer = 5, Optional ByVal a As Integer = 10) As Integer

Return x + y + z + a

End Function


From the above code, it has 2 optional parameter. we can't pass value to parameter "a" without passing value for parameter "z".


// Calling
Add(1, 2, 5, 15)


C# 4.0 - Named Parameter
public int Add(int x, int y, int z = 5, int a = 10)
{
return x + y + z + a;
}


//calling
Add(1,2,a:15);


From the above code, it has 2 optional parameter. But here we can pass a value to parameter "a" without passing a value for "z" by using name of parameter like a:15.

No comments: