Using collection initializer inside object initializer C# with Example



Using collection initializer inside object initializer C# with Example

public class Tag 
{ 
public IList Synonyms { get; set; } 
} 
Synonyms is a collection-type property. When the Tag object is created using object initializer syntax, Synonyms can 
also be initialized with collection initializer syntax: 
Tag t = new Tag 
{ 
Synonyms = new List {"c#", "c-sharp"} 
}; 
The collection property can be readonly and still support collection initializer syntax. Consider this modified 
example (Synonyms property now has a private setter): 
public class Tag 
{ 
public Tag() 
{ 
Synonyms = new List(); 
} 
 

public IList Synonyms { get; private set; } 
} 
A new Tag object can be created like this: 
Tag t = new Tag 
{ 
Synonyms = {"c#", "c-sharp"} 
}; 
This works because collection initializers are just syntatic sugar over calls to Add(). There's no new list being created 
here, the compiler is just generating calls to Add() on the exiting object. 

0 Comment's

Comment Form