Sunday, June 7, 2009

PyDictionary

Very simple (not complete) Python-style dictionary in .NET 4.0 using dynamic objects. Allows for arbitrary members to be created and used on the fly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace TestApplication
{
class PyDictionary : DynamicObject
{
private Dictionary<string, object> m_state =
new Dictionary<string,object>();

public override IEnumerable<string> GetDynamicMemberNames()
{
return m_state.Keys;
}

public override bool TrySetMember(SetMemberBinder binder,
object value)
{
m_state[binder.Name] = value;
return true;
}

public override bool TryGetMember(GetMemberBinder binder,
out object result)
{
result = m_state[binder.Name];
return true;
}
};

class Program
{
static void Main(string[] args)
{
dynamic baby = new PyDictionary();

baby.Name = "Alyssa";
baby.Age = 0.8f;

Console.WriteLine(baby.Name + " is " + baby.Age + " years old!");

// I will throw a KeyNotFoundException
int iq = baby.IQ;
}
}

No comments: