简体   繁体   中英

Named Parameters vs Optional Parameters

The optional parameters are nothing new in C# and I've known about that since the release of C# 5.0 but there is something I just came across. When I use Data Annotations for my MVC models such as the Required attribute I see this:

在此处输入图片说明

So I can do:

[Required(ErrorMessage="Something"]

However when I create my own methods with optional parameters like:

void Test(String x = null, String y = null) {}

I can pass arguments in both these ways:

Test(x = "Test") OR Test(x: "Test")

this while in the Required attribute I always have to use the = and if I use the : it will cause error. for example:

 Required(ErrorMessage:"Something") --> Compile time error

So what I see is that those Named Parameters are created differently than what I already knew about. And my question is How to make them for a method (How to create such Named Parameters like in the Required attribute).

An attribute has its own syntax. It uses the name=value form for named parameters.

For a normal method you can't use that form, you are stuck with the name:value form.

It would not be possible to use the name=value form for normal methods. The compiler would not be able to tell if you were trying to use a named parameter or if you were trying to assing a value to a variable and use the assignment as a parameter value.

Despite this syntax looking like a method call:

[Required(ErrorMessage="Something")]

An Attribute is a class , not a method. You aren't specifying an argument in the line above, you are initializing a property. See the example on the Attribute base class documentation to see what I mean.

The Attribute-specifying syntax is therefore similar to C#'s class initialization syntax:

new RequiredAttribute { ErrorMessage = "Something" };

There is currently no equivalent syntax in C# for specifying a named argument to a method.

If you do something like:

string y; 
Test(y = "Test")

You can call a function with that syntax. But be careful... the y = "Test" is actually setting the variable y , and then passing that to the function! There is a side-effect there which is probably undesirable. Also "Test" is getting passed into parameter x of the Test function, not y because it's going in as the first parameter.

In short, you should always avoid using this syntax when calling a function, because it doesn't do what you're expecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM