Click here to Skip to main content
15,888,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm a beginner in C# and I would like to know of both ways down are equal?
Is the first 4 lines of code are the same as the last 2 lines?

C#
var genre = new Genre()
{
   Name = "Search results for " + q
};
//--------------------------------------  
      
Genre newGenre = new Genre();
newGenre.Name = "Search results for" + q;
Posted
Comments
CPallini 13-Sep-13 4:43am    
Maybe I am wrong, but the first alternative doesn't look valid code to me.
(I was indeed wrong)
Thomas Barbare 13-Sep-13 4:45am    
It's valid, why do you think it's not ?
CPallini 13-Sep-13 5:30am    
I'm not a C# expert, that's all. What is it?
Thomas Barbare 13-Sep-13 5:35am    
Oh ok, I quote MSDN :

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
CPallini 13-Sep-13 5:44am    
OK, I got it. Thank you.

1 solution

Both ways are equal but you'll see the second way more often because it is easier to read for most. It is more clear as to what you are doing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900