views:

368

answers:

2

with PHP optional parameters, if you don't send a parameter it will be assigned to a default value:

public function getCustomer(id, optionalMessage = "(no message)") {
    ...
}

in C# I generally solve this with C# method overloading, e.g.:

public void GetCustomer(int id) 
{
    ...
}

public void GetCustomer(int id, string optionalMessage)
{
    ...
}

but I miss the pragmatic PHP variant, does C# also have some sugary syntax to do optional parameters as well, as in the PHP example?

+8  A: 

Not in C# 3.0; this feature is on the sheet for C# 4.0 - see here.

For now, you'll have to use different overloads:

public void Foo(int a) {Foo(a, "");}
public void Foo(int a, string b) {...}

The proposed syntax would be:

public void Foo(int a, string b = "") {...}

called with any of:

Foo(123); // use default b
Foo(123, "abc"); // optional by position
Foo(123, b: "abc"); // optional  by name
Marc Gravell
your blog post pointed out the reason why I asked: I was seeing the it almost solved with named parameters (e.g. in custom attributes) but it wasn't 100% there (as you suggest there have to be setters), nice, thanks
Edward Tanguay
+4  A: 

No, but you can simulate them to an extent, particularly if your optional parameters are of the same type (or you don't mind doing some casting).

You can use the params flag.

void paramsExample(object arg1, object arg2, params object[] argsRest)

I should point out though, this loses type safety, and there is no type enforcement of the parameters or order.

Mystere Man