Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon Parameters in C#, What does the colon stands for [duplicate]

Tags:

c#

c#-5.0

c#-4.0

In some functions while passing data i had seen syntax like this

obj = new demo("http://www.ajsldf.com", useDefault: true);

What is the meaning of : here and how it is different from other parameters which we pass in the methods.

like image 566
Mohit Avatar asked Sep 30 '14 05:09

Mohit


1 Answers

They are Named Arguments. They allow you to provide some context to the function argument you are passing in.

They must be last .. after all non-named arguments when calling a function. If there is more than one, they can be passed in any order.. as long as they come after any non-named ones.

E.g: this is wrong:

MyFunction(useDefault: true, other, args, here)

This is fine:

MyFunction(other, args, here, useDefault: true)

Where MyFunction might be defined as:

void MyFunction(string other1, string other2, string other3, bool useDefault)

This means, you can also do this:

MyFunction(
    other1: "Arg 1",
    other2: "Arg 2",
    other3: "Arg 3",
    useDefault: true
)

This can be really nice when you need to provide some context in an otherwise hard to comprehend function call. Take MVC routing for example, its hard to tell what's happening here:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

If you look at the definition .. it makes sense:

public static Route MapRoute(
    this RouteCollection routes,
    string name,
    string url,
    Object defaults
)

Whereas, with named arguments, its much easier to comprehend without looking at the documentation:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
like image 73
Simon Whitehead Avatar answered Sep 29 '22 06:09

Simon Whitehead