Custom Collection Initializers

Posted by Jake on Stack Overflow See other posts from Stack Overflow or by Jake
Published on 2010-03-22T21:12:09Z Indexed on 2010/03/22 21:21 UTC
Read the original article Hit count: 389

Filed under:

Classes that implement IEnumerable and provide a public void Add(/* args */) function can be initialized like in the following example:

List<int> numbers = new List<int>{ 1, 2, 3 };

which calls the Add(int) function 3x after initializing the List<int>.

Is there a way to define this behavior explicitly for my own classes? For example, could I have the initializer call a function other than the appropriate Add() overload?

© Stack Overflow or respective owner

Related posts about c#