C# method call with parameter name and colon

心已入冬 提交于 2019-11-28 08:03:48

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.

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.

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);
}
CD..

Scott Gu has introduced this new feature in his blog:

Optional Parameters and Named Arguments in C# 4

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

@Krumelur said that "Named parameters are standard in ObjectiveC for instance."

That's not actually correct. Objective-C uses an infix notation, so that this message call:

[foo setRed:255 Green:255 Blue:0];

is the setRed:Green:Blue: message (including those colons!) with the (255,255,0) arguments interspersed within the message name.

Although, granted, at first blush Objective-C's syntax gives the appearance that Objective-C uses named parameters. But that is not actually correct, and misunderstanding the difference can be an impediment for learning Objective-C.

(I would have answered in a comment, but I somehow lost all my reputation points and I'm starting over. Drat. C'est la vie.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!