Skip to content

Instantly share code, notes, and snippets.

@elylucas
Created August 10, 2010 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elylucas/517890 to your computer and use it in GitHub Desktop.
Save elylucas/517890 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
dynamic param = new DynamicParam();
param.Message = "monkey";
param.SayHi = new Action<string> (s => Console.WriteLine(s));
DoStuff(param);
Console.ReadLine();
}
static void DoStuff(dynamic args)
{
Console.WriteLine(args.Message); //This param is required since we don't check if exists or not
if(args.HasTitle) //Check to see if args Has a Title param, since we don't this statement doesn't execute
Console.WriteLine(args.Title);
if(args.HasSayHi) //Check to see if args Has a SayHi method
args.SayHi("h22i");
}
}
class DynamicParam : DynamicObject
{
private Dictionary<string, object> _members = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder.Name.StartsWith("Has"))
{
var name = binder.Name.Substring(3);
if (_members.ContainsKey(name))
result = true;
else
result = false;
return true;
}
else
{
if (_members.ContainsKey(binder.Name))
{
result = _members[binder.Name];
return true;
}
else
{
result = false;
return true;
}
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!_members.ContainsKey(binder.Name))
_members.Add(binder.Name, value);
else
_members[binder.Name] = value;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment