.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

2 Comments

Comments have been disabled for this content.