James
James

Reputation: 143

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:

enter image description here

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).

Upvotes: 2

Views: 195

Answers (3)

The Vermilion Wizard
The Vermilion Wizard

Reputation: 5415

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.

Upvotes: 0

Dan J
Dan J

Reputation: 16718

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.

Upvotes: 2

Guffa
Guffa

Reputation: 700840

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.

Upvotes: 4

Related Questions