Optional Parameters in C# 4.0

People complain all the time that Microsoft steals their .NET ideas from other languages. If you read our post on BigInteger, you’ll know Microsoft has their eyes on Java.

Well, starting in .NET 4.0, they’ve added another great feature from other languages like PHP — optional parameters! I can’t think of a real-world situation right now of where you would use this, so humour the contrived example:


private string Sum(int a, int b, int c = 0) {
return a + b + c;
}

// Sum(2, 3); // returns 5
// Sum(2, 3, 1); // returns 6

This illustrates two requirements of optional parameters (which all PHP programmers are already familiar with):

  • At the End: Optional parameters must be the last parameters in the method. You can’t have non-optional parameters before them.
  • Default Value: Optional parameters have to have some sort of default value.

Now, this could potentially allow people to write one huge, parameter-laden method instead of several overloads with various numbers of parameters; but whether that’s a good idea or not is really a design decision.

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *