Last active
December 16, 2015 14:49
-
-
Save n3rd/5451555 to your computer and use it in GitHub Desktop.
Exploring the C# Dynamic Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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