Kredns
Kredns

Reputation: 37201

Named/Optional parameters in C# 3.0?

Is there a way to add optional parameters to C# 3.0 like there will be in C# 4.0? I gotta have this feature, I just can't wait!

Edit:

If you know a work-around/hack to accomplish this, post it also. Thanks!

Upvotes: 2

Views: 5459

Answers (5)

Matt Hamilton
Matt Hamilton

Reputation: 204129

You can use an anonymous type and reflection as a workaround to named parameters:

public void Foo<T>(T parameters)
{
    var dict = typeof(T).GetProperties()
        .ToDictionary(p => p.Name, 
            p => p.GetValue(parameters, null));

    if (dict.ContainsKey("Message"))
    {
        Console.WriteLine(dict["Message"]);
    }
}

So now I can call Foo like this:

Foo(new { Message = "Hello World" });

... and it will write my message.

Basically I'm extracting all the properties from the anonymous type that was passed, and converting them into a dictionary of string and object (the name of the property and its value).

Upvotes: 13

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

One could also use variable arguments as option parameters. An example of the way this works is string.Format().

See here:

http://blogs.msdn.com/csharpfaq/archive/2004/05/13/131493.aspx

Upvotes: 2

Andy White
Andy White

Reputation: 88345

Like Dustin said, optional parameters are coming in C# 4.0. One kind of crappy way to simulate optional parameters would be to have an object[] (or more strongly-typed array) as your last argument.

Upvotes: 4

Andrew Arnott
Andrew Arnott

Reputation: 81781

There's always method overloading. :)

Upvotes: 9

Dustin Campbell
Dustin Campbell

Reputation: 9855

Unfortunately, no. You will need the C# 4.0 compiler to support this. If you want optional parameters on the .NET platform today, you can try VB .NET or F#.

Upvotes: 8

Related Questions