Question

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!

Was it helpful?

Solution

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).

OTHER TIPS

There's always method overloading. :)

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#.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top