How to define named Parameters C#

Pierluc SS picture Pierluc SS · Aug 21, 2012 · Viewed 15.1k times · Source

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

Answer

Daniel Hilgarth picture Daniel Hilgarth · Aug 21, 2012

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.