Sunday, November 8, 2009

C# 4.0 - Optional Parameters

With .net framework 4.0 and C# 4.0 also introduces a new feature called optional parameters it was there in VB since visual basic 6.0. But it is now available in the C# with 4.0 version. Optional parameter will be become very handy when you don't want to pass some parameter and just you need the default value. For that Till C# 3.0 we need to create overloaded functions where we creating function with different argument with same function name. Let's see how its works

Let's go through a simple scenario we will create function with simple response.write which will print a string which will be optional argument.

Code Snippet

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. PrintMessage();
  4. PrintMessage("This is message to print passed as argument");
  5. }
  6. private void PrintMessage(string MessageToPrint="This is default message to print")
  7. {
  8. Response.Write(MessageToPrint);
  9. }

See the above example in that we have created one created once function PrintMessage which will print message on web page thorough Response.Write. And in the Page_Load event we called two times first one is which without argument which will print default message and another one which will have message an message argument which will print message which we have passed. Lets run that application and following out put will produced.


So that's it it will work like this if you passed argument the it will use argument or otherwise its will use the default argument. This will become handy and you don't need to write overloaded function with default value.

Happy Programming ...

Technorati Tags: ,,
Shout it


Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews