Reputation: 2473
I was going a through a MVC tutorial when I bump into this:
public ActionResult Index()
{
dynamic genres = new List<Genre> {
new Genre { Name = "Disco" },
new Genre { Name = "Jazz" },
new Genre { Name = "Rock" }
};
return View(genres);
}
What is the difference if I use Genre.Add("Disco");
... instead. Thanks.
Upvotes: 1
Views: 167
Reputation: 64467
I presume you mean the difference between that and genres.Add
(the List<T>.Add
method) as Genre.Add
might be a static method on Genre
or an instance method on a Genre
variable, neither of which have been posted.
There is no behavioural difference in the final code, it is only a visual difference.
Not sure why you are using dynamic
(perhaps you are looking for var
?), but the difference is that this is called collection initialization syntax, basically sugar over calling .Add
manually:
var genres = new List<Genre> {
new Genre { Name = "Disco" },
new Genre { Name = "Jazz" },
new Genre { Name = "Rock" }
};
Is equivalent to:
var genres = new List<Genre>();
genres.Add(new Genre { Name = "Disco" });
genres.Add(new Genre { Name = "Jazz" });
genres.Add(new Genre { Name = "Rock" });
The compiler outputs the .Add
for you in your case.
Whats the difference between these three ways of creating a new List<string> in C#?
Also in your example, you are seeing the object initializer syntax with:
new Genre { Name = "Disco" }
Which equates to:
var g = new Genre();
g.Name = "Disco";
Upvotes: 3
Reputation: 1499810
It's not clear why you're using dynamic
here to start with, to be honest. But if you used
List<Genre> genres = new List<Genre>();
genres.Add(new Genre { Name = "Disco" });
genres.Add(new Genre { Name = "Jazz" });
genres.Add(new Genre { Name = "Rock" });
it would have the same effect.
Note that it's genres.Add
, not Genre.Add
.
I'd also suggest that if you create a Genre constructor taking the name, it will make the code simpler - or if you want to still make the name part explicit, you could create a Genre.FromName
static method.
Upvotes: 3
Reputation: 68667
In compiled terms none. It's actually syntax sugar for
dynamic genres = new List<Genre();
genres.Add(new Genre...
This is what I assume you meant, since Genre.Add(string)
isn't described.
Upvotes: 1