What value do you think named and default parameters will add in C#.Net 4.0?
What would be a good use for these (that hasn’t already been achieved with overloading and overriding)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It can make constructors simpler, especially for immutable types (which are important for threading) – see here for a full discussion. Not as nice as it should be perhaps, but nicer than having lots of overloads. You obviously can’t use object initializers with immutable objects, so the usual:
isn’t available; I’ll settle for:
This can be extended to the general idea of simplifying overloads, but in most cases I’d prefer overloads that advertise the legal combinations. Constructors are a bit different, IMO, since you are just (typically) defining the initial state.
The COM side of things is also important to a lot of people, but I simply don’t use much COM interop – so this isn’t as important to me.
Edit re comments; why didn’t they just use the same syntax that attributes use? Simple – it can be ambiguous with other members / variables (which isn’t an issue with attributes); take the example:
which uses one regular parameter (to the ctor, ‘foo’), and one named assignment. So suppose we use this for regular named arguments:
(which could also be a constructor; I’ve used a method for simplicity)
Now… what if we have a variable or a property called
SecondArg? This would be ambiguous between usingSecondArgas a named argument toSomeMethod, and assigning ‘bar’ toSecondArg, and passing ‘bar’ as a regular argument.To illustrate, this is legal in C# 3.0:
Obviously, SecondArg could be a property, field, varialble, etc…
The alternative syntax doesn’t have this ambiguity.
Edit – this section by 280Z28: Sorry for adding this here, but it’s not really a unique answer and it’s too long for the comments and includes code. You hinted at the ambiguity but your example didn’t highlight the deciding case. I think the example you gave points out something that could be confusing, but the required
{}around object initializers prevents an underlying syntactical ambiguity. My explanation for the following code is embedded as the multi-line block comment.