One of the amazing features from C#
4.0 is “Optional Parameters”. It was a feature of VB.Net but it’s now available
in C# too.
I’m not so much involved in this,
but I do think there will be some situations where this will be useful to make
code more concise.
Consider a standard situation with
method overloading or constructor chaining. In C# we’d have several
methods with different signatures where, in effect, we’re indeed just after
default values.
Let’s take the consequence where we’ve got a little helper
class to send emails in our application. In some cases we want to CC the
administrator to troubleshoot issues; in some cases we want rich HTML emails rather
than plain text. We might set up our methods like this:
public void SendMail(string ToAddress, string
Body)
{
this.SendMail(ToAddress, Body, true);
}
public void SendMail(string ToAddress, string
Body, bool CcAdministrator)
{
this.SendMail(ToAddress, Body, CcAdministrator, false);
}
public void SendMail(string ToAddress, string
Body, bool CcAdministrator, bool IsBodyHtml)
{
// the whole Implementation goes here
}
This is a typical method overloading concept and basically
we will set default values (true for CC the Admin, and false for HTML emails).
With new C# 4.0 we can now make the
code more short by only having to implement 1 method:
public void SendMail(string ToAddress, string
Body, bool CcAdministrator = true, bool IsBodyHtml
= false)
{
// the whole Implementation goes here
}
Now the Magic Begins!
If I call the method by passing a
least parameters like this
SendMail("shreekumar@donreturns.com",
"This time my return is huge!");
The IL (Intermediate Language) that
the C# compiler will generate will actually be the equivalent of this: [See the
default values for CcAdministrator and IsBodyHtml]
SendMail("shreekumar@donreturns.com",
"This time my return is huge!", true, false);
Another good thing is, here we’ve
the ability to skip any parameter (say by skipping a 3rd parameter CcAdministrator and pass 4th
parameter IsBodyHtml in a function call) like this
SendMail("shreekumar@donreturns.com",
"This time my return is huge!", IsBodyHtml:true);
This will allow the code to only
pass 3 arguments for conciseness but still invoke the appropriate overload
since the IL generated in that instance will be equivalent to this:
SendMail("shreekumar@donreturns.com",
"This time my return is huge!", true, true);
Finally, I can say that “Overall It’s a great feature in C# library if used in the correct situations, it can improve our code efficiency greatly”
No comments:
Post a Comment