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.
- protected void Page_Load(object sender, EventArgs e)
- {
- PrintMessage();
- PrintMessage("This is message to print passed as argument");
- }
- private void PrintMessage(string MessageToPrint="This is default message to print")
- {
- Response.Write(MessageToPrint);
- }
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 ...
HI..
ReplyDeleteHello Amit
ReplyDelete