Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

.Net Framework 4.0: C# and optional arguments and named parameters

C# 4.0 supports optional method arguments. Related to this is support for named parameters in function calls. For us it makes easier to use methods which have long argument list. It also introduces some new dangers which may lead us to messy and hard to understand code. In this code I will show how to use optional arguments and give some hints how to avoid messy code.

I wrote simple application to illustrate default values and their usage.


class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine(GetArguments("one"));

        Console.WriteLine(GetArguments("one", "four"));

        Console.WriteLine(GetArguments("one", "four", "five"));

        Console.WriteLine(GetArguments("one", third:"five"));           

 

        Console.WriteLine("Press any key to exit...");

        Console.ReadLine();

    }

 

    private static string GetArguments(string first,
                string
second = "two", string third="three")

    {

        return first + " " + second + " " + third;

    }

}


csharp-optional-arguments-outputExample (not exact) output of this program is shown on image on right.

First three calls to GetArguments() are not something crucial and they follow current C# syntax.

Fourth call introduces named parameter. Notice how we are giving value to first and third argument. Syntax is very simple: parameter:value.

Use carefully

Optional arguments are widely used in VBA for long time. Although they make life a little bit easier for programmers (you don’t have to repeat default values in your method calls) there will be always danger that optional arguments are overused.

Too long argument lists refers to the need of parameter object (refactoring method called Introduce Parameter Object). Parameter object may also carry default values because you can assign initial values to object attributes and properties.

Of course, it is up to you and depends on context if you want to use method with many arguments or parameter object. If you know pitfalls then it is easier for you to make decisions.


kick it on DotNetKicks.com pimp it Progg it 顶 Shout it
Posted: Aug 19 2009, 02:11 AM by DigiMortal | with 9 comment(s)
Filed under: ,

Comments

AndrewSeven said:

Given the potential pitfalls, method overloading and parameter object should be the first choices.

# August 19, 2009 8:52 AM

dinoboy said:

A good post about optional parameters internals - devlicio.us/.../thoughts-on-c-4-0-optional-parameters.aspx

# September 9, 2009 2:54 AM