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.
I presume you mean the difference between that and
genres.Add(theList<T>.Addmethod) asGenre.Addmight be a static method onGenreor an instance method on aGenrevariable, 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 forvar?), but the difference is that this is called collection initialization syntax, basically sugar over calling.Addmanually:Is equivalent to:
The compiler outputs the
.Addfor 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:
Which equates to: