Skip to content

Instantly share code, notes, and snippets.

@thecodejunkie
Created January 25, 2011 21:00
Show Gist options
  • Save thecodejunkie/795650 to your computer and use it in GitHub Desktop.
Save thecodejunkie/795650 to your computer and use it in GitHub Desktop.
implicit cast operators on the dynamicdictionaryvalue
namespace ConsoleApplication1
{
using System.Dynamic;
class Program
{
static void Main(string[] args)
{
dynamic dictionary = new DynamicDictionary();
dictionary.foo = "test";
dictionary.bar = Guid.NewGuid();
var worker = new Worker();
worker.DoWork(dictionary.foo, dictionary.bar);
Console.ReadLine();
}
}
public class Worker
{
public void DoWork(string value, Guid id)
{
Console.WriteLine(value);
Console.WriteLine(id.ToString());
}
}
public class DynamicDictionary : DynamicObject
{
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return dictionary.TryGetValue(binder.Name, out result);
}
public dynamic this[string name]
{
get { return dictionary[name]; }
set { dictionary[name] = value is DynamicDictionaryValue ? value : new DynamicDictionaryValue(value); }
}
}
public class DynamicDictionaryValue : DynamicObject
{
public DynamicDictionaryValue(object value)
{
Value = value;
}
private object Value { get; set; }
public static implicit operator string(DynamicDictionaryValue d)
{
return Convert.ToString(d.Value);
}
public static implicit operator Guid(DynamicDictionaryValue d)
{
return (Guid)d.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment