Zann Anderson
Zann Anderson

Reputation: 4907

C# method call with parameter name and colon

I've begun to notice at times when I'm making method calls in C# that the names of the parameters for the method I'm calling will show up in the intellisense list appended with a colon, and that I can then format the method call thusly:

MethodCall(parameter1:value1, parameter2:value2);

Is this a new language feature? It reminds me of the way you can call stored procedures in SQL and specify parameter names like so:

spDoSomeStuff @param1 = 1, @param2 = 'other param'

Is this a similar feature? If so, to what end? If not, what is it and what is it to be used for.

Upvotes: 54

Views: 40935

Answers (5)

vent
vent

Reputation: 1063

It is worth mentioning, unlike optional parameters, you can skip certain arguments and pass only the parameters you are interested in.

public void Example(int required, string StrVal = "default", int IntVal = 0)
{
    // ...
}

public void Test()
{
    // This gives compiler error
    // Example(1, 10);

    // This works
    Example(1, IntVal:10);
}

Upvotes: 29

CD..
CD..

Reputation: 74146

Scott Gu has introduced this new feature in his blog:

Optional Parameters and Named Arguments in C# 4

Upvotes: 6

Brandon Moretz
Brandon Moretz

Reputation: 7621

Named parameters allow you explicitly set the value of arguments in a custom order independent of the signature. Method signatures are defined by the argument types, ie, Foo( int i, bool b ), which will only accept arguments of type int and bool in that order. Named arguments allow you to pass b first and i second.

Upvotes: 24

ChrisF
ChrisF

Reputation: 137148

It's the Named and Optional Parameters that came in with C# 4.

Upvotes: 3

Krumelur
Krumelur

Reputation: 33048

It's a new feature. See here: http://msdn.microsoft.com/en-us/library/dd264739.aspx Named parameters are standard in ObjectiveC for instance. It takes some time to get used to them but they are a good thing. Only from looking you can tell what a parameter is meant for.

Upvotes: 49

Related Questions