Collection initializers in custom classes C# with Example



Collection initializers in custom classes C# with Example

To make a class support collection initializers, it must implement IEnumerable interface and have at least one Add 
method. Since C# 6, any collection implementing IEnumerable can be extended with custom Add methods using 
extension methods. 
class Program 
{ 
static void Main() 
{ 
var col = new MyCollection { 
"foo", 
{ "bar", 3 }, 
 

"baz", 
123.45d, 
}; 
} 
} 
class MyCollection : IEnumerable 
{ 
private IList list = new ArrayList(); 
public void Add(string item) 
{ 
list.Add(item) 
} 
public void Add(string item, int count) 
{ 
for(int i=0;i< count;i++) { 
list.Add(item); 
} 
} 
public IEnumerator GetEnumerator() 
{ 
return list.GetEnumerator(); 
} 
} 
static class MyCollectionExtensions 
{ 
public static void Add(this MyCollection @this, double value) => 
@this.Add(value.ToString()); 
} 

0 Comment's

Comment Form

Submit Comment