Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define named Parameters C#

This seems like a simple question, but for some reason I can't find the answer anywhere. Basically, I'd like to be able to implement a constructor that takes NamedParameters.

By named parameters, I do not mean parameters with default values (optional parameters) such as:

public SomeMethod(){
    string newBar = Foo(bar2 : "customBar2");
}

public string Foo(string bar1 = "bar1", bar2 = "bar2" ){
     //...
}

A good example of what I'm trying to achieve is the AuthorizeAttribute from the System.Web.Mvc assembly. Which you can use the following way:

[Authorize(Roles = "Administrators", Users = "ThatCoolGuy")]
public ActionResult Admin(){

}

The constructor's signature in intellisense looks like the following example and I believe (please confirm) that those NamedParameters are mapping to class properties.

AuthorizeAttribute.AuthorizeAttribute(NamedParameters...) Initiliaze new instance of the System.Web.Mvc.AuthorizeAttribute class

Named parameters:

  • Order int
  • Users string
  • Roles string
like image 550
Pierluc SS Avatar asked Aug 21 '12 14:08

Pierluc SS


People also ask

How do you pass parameters to a name?

When you pass an argument by name, you specify the argument's declared name followed by a colon and an equal sign ( := ), followed by the argument value. You can supply named arguments in any order. When you call this procedure, you can supply the arguments by position, by name, or by using a mixture of both.

What is named parameters in C#?

Named Parameter Named Parameters allow developers to pass a method arguments with parameter names. Prior to these this feature, the method parameters were passed using a sequence only. Now, using named parameters in C#, we can put any parameter in any sequence as long as the name is there.

Why do we use named parameters?

Named arguments can improve the readability and safety of your code.

How do you declare a parameter in C#?

In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment.


2 Answers

Please note:

The syntax of defining the parameter name when calling a method has nothing to do with optional parameters:

You can use Foo(bar1 : "customBar1"); even if Foo is declared like this: void Foo(string bar1)


To answer the question:
My guess is that this is syntactic sugar similar to the object initializers introduced in Visual Studio 2010 and therefore you can't use this for your own classes.

like image 187
Daniel Hilgarth Avatar answered Oct 13 '22 01:10

Daniel Hilgarth


The behaviour you are talking about is specific for attributes and cannot be reused in "normal" classes constructors.

like image 31
mathieu Avatar answered Oct 12 '22 23:10

mathieu