Create a gist now

Instantly share code, notes, and snippets.

@n3rd /Dynamic.cs
Last active Dec 16, 2015

What would you like to do?
Exploring the C# Dynamic Type
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace DynamicTest
{
class Program
{
static void Main(string[] args)
{
dynamic test = new MyDynamicObject();
test.FirstName = "Boaz";
Console.WriteLine(test.FirstName);
// RuntimeException:
//Console.WriteLine(test.LastName);
dynamic exp = new ExpandoObject();
exp.FirstName = "Boaz";
Console.WriteLine(exp.FirstName);
// RuntimeException:
//Console.WriteLine(exp.LastName);
Console.WriteLine(Add(1, 2));
Console.WriteLine(Add("Bo", "az"));
A a = new A() { FirstName = "Boaz object A" };
B b = new B() { FirstName = "Boaz object B" };
PrintDynamic(a);
PrintDynamic(b);
PrintObject(a);
// NullreferenceExcption at runtime!
//PrintObject(b);
Console.ReadKey();
}
static dynamic Add(dynamic a, dynamic b)
{
return a + b;
}
static void PrintObject(object x)
{
A y = x as A;
Console.WriteLine(y.FirstName);
}
static void PrintDynamic(dynamic x)
{
Console.WriteLine(x.FirstName);
}
}
class A
{
public string FirstName { get; set; }
}
class B
{
public string FirstName { get; set; }
}
class MyDynamicObject : DynamicObject
{
Dictionary<string, object> _Values = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_Values.ContainsKey(binder.Name))
result = _Values[binder.Name];
else
result = null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!_Values.ContainsKey(binder.Name))
_Values.Add(binder.Name, value);
else
_Values[binder.Name] = value;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment