Handling optional parameters in C#

ANALYSIS While most modern programming languages provide some way of declaring optional function parameters, C# doesn't provide a way of directly doing so, despite the fact that VB.Net and .Net's attribute system both support this functionality. This is a subject of some debate currently in the C# community. The C# development team's position seems to boil down to the following: When provided, this feature is usually nothing more than dressing up method overloading with a little syntactic sugar. When you get right down to it, their position makes some sense. A function with an optional parameter is in reality two different functions: one that assumes some default behavior if the optional parameter is omitted, and another that performs more specific behavior based on the value of the optional parameter if provided. But that doesn't change the fact that using overloaded methods to provide optional parameter support feels a little clunky. It works, but you always wind up writing more code, and you pollute your object interface with the extra method signatures required to support all of your optional parameters. Let's look at some alternatives. Parameter arrays If you take a look at the classes found in the common language runtime (CLR), you'll find more than a few with methods that can accept a variable-length list of parameters. One example would be the System.Console.WriteLine method, which has an overloaded declaration that works to support replaceable parameters in the string written to the console. For example, this code: Console.WriteLine("{0} jumped over {1}.", "The cow", "the moon");
produces the following output:
The cow jumped over the moon. Any number of replaceable parameters can be specified in this fashion, which means that the number of arguments passed to the WriteLine method can vary from call to call. C# supports this behavior with the params keyword, which, when used before an array type in a function's argument list, creates a parameter array. You can use this array to fake optional parameters in practice. Check out Listing A for an example of this in action. You can see that this solution works pretty well. The OptionalStrings method may be legally called with no parameters, in which case the parameter array args is simply empty -- in effect, the entire array is optional. Further, the calling function doesn't need to explicitly wrap the parameters it sends in an array, and since the parameter array is an honest-to-goodness array, the called function can easily determine how many parameters it has received. But there are a few caveats:
  • There's no enforceable limit to the number of arguments received in this way. You couldn't, for instance, declare the OptionalStrings method to receive a maximum of three optional arguments without writing code to do so at runtime inside the function itself.
  • Similarly, there's no way to make the array typesafe. If you need to support multiple types in the parameter array, you're limited to using a lowest-common-denominator approach, usually declaring the parameter array as type Object.
  • Only one parameter may be marked using params, and it must be the last parameter in the method's argument list.
  • You can't specify an optional out (passed by reference) parameter using this method.
An object-oriented solution Another possible solution would be to create a class encapsulating all the possible arguments a method could receive, and pass an instance of that class to the method in question. This approach makes sense from an object-oriented point of view and solves the problems I pointed out with the parameter array solution, as you can see from Listing B. By creating a default, parameterless constructor for the ParameterClass class, I can set whatever default values I want for the public fields, which represent the possible parameters for the OptionalObjects method. I just override any of the fields I'm interested in actually providing a value for, and pass the whole object to OptionalObjects. Because objects are passed by reference, any changes made to a ParameterClass field while inside the OptionalObjects method are reflected when the method returns. In effect, the whole object is an out parameter. Not only does this provide a neat solution to the optional parameter conundrum, but passing arguments in the form of objects also serves to further insulate your classes from one another. It's possible, using this method, to add additional arguments for OptionalObjects with a minimum of fuss. Simply redefining ParameterClass to contain the new fields is all that's required. Not perfect, but it works None of these solutions is perfect, but they all enable you to fake your way into supporting optional parameters in your applications. Since the last word received from Microsoft seems to indicate that built-in optional parameter support will not be forthcoming, we'll have to get by with workarounds like these.
Have your say instantly in the
Tech Update forum. Find out what's where in the new Tech Update with our
Guided Tour. Let the editors know what you think in the
Mailroom.

Talkback

This is a nice article. (one of very few articles available in the internet) on how to get around optional parameters in C#. Some of the hyperlinks like listingA and listingB don't work.
It will be very helpful if we could see your code sample. Thanks.

26 Aug 03 21:29 Reply

Nice article.
I found this while searching for a solution/way using optional parameter at C#.
It is very bad that C# doesn't have optional parameters. No solution is good as natural support :(

24 Mar 06 00:20 Reply

Post your comment

In order to post a comment you need to be registered and logged in

Log in or create your ZDNet UK account below

Will not be displayed with your comment

By signing up for this service, you indicate that you agree to our Terms and Conditions and have read and understood our Privacy Policy. Questions about membership? Find the answers in the Membership FAQ

ZDNet UK Live

sameerhere

the future of mobile will be location and context aware. This means, you will have apps that will suggest you depending where you are right...

27 minutes ago by sameerhere on Symbian^3 will do resistive multitouch, says Nokia
kenye2009

hello i would like to have some form of a answer to this question as it concerns the goverment i want to know why if your on state benefits as a...

43 minutes ago by kenye2009 on ITN to launch ITV online news service
georgiox

love the LHC info. Keep up the good work. May God bless all in volved.

7 hours ago by georgiox on LHC to run for longest continuous period
sgardia

You are quite right. HDS has not been marketing their products well. USPV is miles ahead in terms of ease of use and technology on enterprise...

12 hours ago by sgardia on Will the SUN set on Hitachi Data Systems OEM relationship?
apexwm

Fedora is the same way as well. The yum update system uses "presto" which shrinks the amount of data needed for download. It's a great system....

22 hours ago by apexwm on Can you believe it - 2765 kB will be freed?
cybfor

Updated ID cards considered for 2012: [zdnet.co.uk] The government is considering introducing a new generation of ID... http://dlvr.it/KpBZ

cybfor

Google, Viacom trade blows in YouTube copyright spat: [zdnet.co.uk] Google and the US media giant Viacom have issued... http://dlvr.it/Knht

CIMITL

Be sure to include an audio option - eg. a beep tone - to intensify and reiterate the action. This will greatly benefit some consumers and give...

1 day ago by CIMITL
DataSecurityUK

Data disposal is really important to get right. There are standards set by UK and US federal governments to ensure that data is kept secure. If...

1 day ago by DataSecurityUK
chaycon1

Online Fiber Optic Certification Join a talented group of professionals, who are dedicated to Fiber Optic Networking technology. The online course...

1 day ago by chaycon1 on BT launches 40Mbps fibre-based broadband
chaycon1

Online Fiber Optic Certification Join a talented group of professionals, who are dedicated to Fiber Optic Networking technology. The online course...

1 day ago by chaycon1 on Google to build gigabit broadband to the home
J.A. Watson

Hi Dava, I'm glad to hear from you, and glad that you see things from the other side. I think that is the most important point of the whole...

1 day ago by J.A. Watson on Ubuntu 10.04 (Lucid Lynx) and the Latest Tempest
dava4444

please please please please please please kill that spam bot.

1 day ago by dava4444 on ZDNet UK: faster, smarter, still IT all the way
253chelisa253

hi

1 day ago by 253chelisa253 on How security will look in 10 years
lezlow

it is only greedy[microsoft]?

1 day ago by lezlow on Researchers break into BitLocker
dava4444

it didn't post the link it's 'Ubuntu 10.04 Lucid Lynx Beta-1 First Look' on youtube :) Dava

1 day ago by dava4444 on Ubuntu 10.04 (Lucid Lynx) and the Latest Tempest
dava4444

Hi James I disagree, Ubuntu needs a GUI update and this one IMO is quite good. your pics show a low res. here's a high res. on YouTube* The...

1 day ago by dava4444 on Ubuntu 10.04 (Lucid Lynx) and the Latest Tempest
dava4444

Hi any news on the comment bot? knocking me back from my own blog is a bit cheeky lol *Mulder to Scully* "I think it has an agenda.." I know, I...

1 day ago by dava4444 on ZDNet UK: faster, smarter, still IT all the way
benny boy

if you look at the Brentwood exchange on samknows it servers 21,000 residential propertiesm, Lowestoft serves 31,000! Come on BT sort yourselves...

1 day ago by benny boy on BT fibre broadband coming to 69 more towns
pbreddit

[programming] H.264 - a sting in the tail http://reddit.com/bfu4q [zdnet.co.uk]

Featured white papers

Achieving PCI Compliance for:Privileged Password Management & Remote Vendor Access

For multi-store outlets, including retail, banking, grocery, gas, hospitality, convenience stores and others, reducing (or avoiding) the cost of in-store system support and maintenance while maintaining compliance with PCI and other requirements has become a strategic challenge.

Download now

Web 2.0 Security Threats: How to Protect Your Enterprise Network

Speaker: Dr. Chenxi Wang, Principal Analyst, Security and Risk Management, Forrester Research, Inc. As Enterprises are increasingly connected to the Internet and as hard organizational boundaries are fast disappearing, security professionals are facing fresh challenges in Enterprise computing.

Download now

MindManager - Tutorial for New Users - Short

This tutorial is for new MindManager users and teaches you how to get started, by creating maps, reading maps and organizing your information.

Download now