Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square bracket syntax in function's parameter in C#?

Tags:

c#

asp.net

I'm learning ASP.NET and stumbled upon this method declaration:

public IQueryable<Product> GetProducts([QueryString("id")] int? categoryId) {.....}

The tutorial said categoryId will be equal to query string "id" (From URL, like &id=5) but the question is what is [QueryString("id")] syntax called? Is this usable outside ASP.NET and what will the application of this be?

like image 479
5argon Avatar asked Mar 28 '13 20:03

5argon


People also ask

What is square bracket used for in C?

Square brackets are used to index (access) elements in arrays and also Strings.

What do square brackets mean in syntax?

The square brackets themselves are not typed. | A vertical bar that separates two or more elements indicates that any one of the elements can be typed. { } If two or more element are enclosed within curly braces and separated by a vertical bar, one of the elements must be typed.

What are square brackets [] used for in a lambda declaration?

The square brackets specify which variables are "captured" by the lambda, and how (by value or reference). Capture means that you can refer to the variable outside the lambda from inside the lambda.


1 Answers

That's applying the QueryStringAttribute attribute to the parameter categoryId. It's just an attribute, just like the ones you're probably more used to seeing on methods or classes, like this:

[STAThread]
static void Main()
{
}

In this case, presumably some part of the framework (I'm not an ASP.NET developer, so I can't point out exactly what) is using reflection to find all the methods, find any QueryStringAttribute values applied to the parameters, and then matching the names within those attributes with the names in the query string, then extracting the matching values to pass into the method call (again using reflection).

like image 116
Jon Skeet Avatar answered Sep 28 '22 13:09

Jon Skeet