Tuesday, February 5, 2013

Passing Null Parameters in C#.NET


.NET framework 4.0 onward you have the ability to pass null parameters in C#.NET. See below example.

private string GetName(string name = null)
{
    string myName=string.Empty;
if (string.IsNullOrEmpty(name))
{
myName = "chamara";
}
else
{
myName = name;
}
   return myName;
}
Calling the method
With Parameter:
GetName("janaka");
Output:
janaka
Without Parameter:
GetName();
Output:
chamara
You can not add null parameters in between or at the start of the parameter list, null parameters are allowed to add only at the end of the parameter list.

Something like below is not allowed.
private string GetName(string name = null, string Address)
{
    //code here
}
private string GetName(string Occupation,string name = null, string Address)
{
    //code here
}

No comments:
Write comments
Recommended Posts × +