Have you ever wondered whether it is possible to create your own collection initializers just like for the List<T>?

var list = new List { 12, 42, 256, 1024 };

Well… doing that is actually extremely simple. All your custom object needs is a public Add method that takes whatever arguments you might want. Don’t try to analyze the code, I know that it doesn’t make any sense at all – it’s just an example

public class MyCollection : IEnumerable
{
	private List _list = new List();

	public void Add(Predicate predicate, T trueValue, T falseValue)
	{
		_list.Add(new MyIfThen { Predicate = predicate, TrueValue = trueValue, FalseValue = falseValue });
	}

	public struct MyIfThen
	{
		public Predicate Predicate;
		public T TrueValue;
		public T FalseValue;
	}

	#region IEnumerable Members

	public IEnumerator GetEnumerator()
	{
		return _list.Select(ifthen => ifthen.TrueValue).GetEnumerator();
	}

	#endregion

	#region IEnumerable Members

	System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
	{
		GetEnumerator();
	}

	#endregion
}

...

var mine = new MyCollection
		   {
			   {i => i%2 == 0, 12, 42},
			   {i => i%3 == 0, 33, 66},
		   };

Leave a Reply

Your email address will not be published.

*