c# - what is this: new[] { } -
this question has answer here:
- what new[] shorthand for? 4 answers
i trying grips asp mvc4 , came across within @{...} within .cshtml file:
@html.dropdownlistfor(x => x.willattend, new[] { new selectlistitem() { text = "yes, i'll there", value = bool.truestring}, new selectlistitem() { text = "no, can't come", value = bool.falsestring} }, "choose option")
q1) kind of thing this: new[]{...}
q2) right in saying razor, stuff within curly brackets c# code.
thanks.
this syntax:
new[] { "foo", "bar", "baz" }
is implicitly typed array initializer. type of array inferred elements within braces. example, above exactly equivalent to:
new string[] { "foo", "bar", "baz" }
in case, new selectitem[] { ... }
.
implicitly typed arrays introduced in c# 3 (but can use them when targeting .net 2.0; they're c# compiler feature). they're partly support using anonymous types, they're useful in other situations too.
within each element in code, however, you've got object initializer, way of creating object , setting properties (or adding collections) within single expression. this:
new selectlistitem() { text = "no, can't come", value = bool.falsestring }
is equivalent to:
selectlistitem tmp = new selectlistitem(); tmp.text = "no, can't come"; tmp.value = bool.falsestring;
... except it's single expression, why you're able use within array initializer. again, object initializers introduced in c# 3.
for razor question - believe so, think rules when piece of text inferred "normal c#" bit more complicated (in order more useful).
Comments
Post a Comment