Friday, August 12, 2011

Is it C#?

Some weird but pretty code trick.

It is c#?
var hash = new Hash
                  {
                   a => "A value", 
                   b => "B value"
                  };
Console.WriteLine(hash["a"]);


Yes, indeed!

This snippet simply use Expressions in such weird way. Here is the implementation of Hash<T> - pretty straightforward, yeah?
	class Hash<t> : IEnumerable<Expression<Func<object, string>>
	{
		private readonly Dictionary<string, T> _dictionary = new Dictionary<string, T>();

		public void Add(Expression<Func<object, string>> item)
		{
			string name = item.Parameters.Single().Name;
			var value = (T) ((ConstantExpression) item.Body).Value;
			_dictionary.Add(name, value);
		}

		public IEnumerator<Expression<Func<object, string>>> GetEnumerator()
		{
			return _dictionary.Select(pair =>
			                          (Expression<Func<object, string>) Expression.Lambda(
			                          	Expression.Constant(pair.Value),
			                          	Expression.Parameter(typeof (object), pair.Key))
				).GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public T this[string name]
		{
			get { return _dictionary[name]; }
			set { _dictionary[name] = value; }
		}
	}

No comments:

Post a Comment