0

I'm studying a book with Membership topic in ASP.NET MVC and I found syntax, I cannot trace (and not explained in the book), which is:

new[] {"string"}

like in:

Roles.AddUsersToRoles(new[] {userName}, new[] {roleName});

Per MDSN library I see Roles.AddUsersToRoles method takes two string arrays as arguments, so likely this is a shorthand or would this have some additional functionality?

Turo
  • 1,537
  • 2
  • 21
  • 42
  • 1
    `new {userName}` presumably is a typo for `new [] {userName}`? – Blorgbeard May 04 '15 at 20:47
  • yes it was a typo, thank you Blorgbeard, and Grant Winney - also a right edit, many thanks. – Turo May 04 '15 at 20:55
  • Fyi, there is also an overload for single user and rolename strings. https://msdn.microsoft.com/en-us/library/system.web.security.roles.addusertorole(v=vs.110).aspx – Tim Schmelter May 04 '15 at 21:02
  • Does this answer your question? [What does new \[\] mean](https://stackoverflow.com/questions/27599213/what-does-new-mean) – Heretic Monkey Mar 30 '22 at 12:28

2 Answers2

8

It is Implicitly Typed Arrays syntax.

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer.

This

string[] stringArray = new[] {"string"};

is same as :

string[] stringArray = new string[] {"string"};

Other thing to note, the method Roles.AddUsersToRoles accepts two parameters of string type array (and not a string).

public static void AddUsersToRoles(
    string[] usernames,
    string[] roleNames
)
Habib
  • 219,104
  • 29
  • 407
  • 436
2
new string[1] { "string" }

You can omit the array size because the compiler can count the number of elements for you:

new string[ ] { "string" }

You can also omit the array element type because the compiler can infer it from the values provided:

new       [ ] { "string" }

But do not get this mixed up with initializers for anonymous types. These do not have the angle brackets [] after new:

new { StringProperty = "string" }

or:

// string StringProperty;
new { StringProperty }
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268