Friday, 22 June 2012

.Net Beginners , C# Tips : Optional and Named Parameters in C#

.Net 4.0 Framework provide Optional and Named Parameters in C# also. Previously it was supported in VB.Net.
Now you do not need to write unnecessary overload methods , With the help of the Optional method you can achieve this.

Here is example of this.

C# Example :
    void DisplayString(int id, string title = "Information", string message = "No Message")
    {
        Response.Write("ID : " +  Convert.ToString( id));
        Response.Write("<br/>Title : " + title);
        Response.Write("<br/>Message : " + message);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DisplayString(10, message: "Hi");
    }

In this example we create one method name "DisplayString" this methods has three parameters , First is Id , Second is Title , This parameter has default value "Information" and Third parameter message , This parameter has also default value "No Message". Now if we called this method with this parameters:

DisplayString(10, message: "Hi"); 

It will display output like this.
Output : 


In this output we pass id as 10 , we do not pass second argument so it takes its default value "Information" , and as second parameter we set name of parameter message , so this parameter property do not take it's default values , it takes pass value "Hi".




2 comments: