Create a Custom Dynamic Type - CSharp Reflection

CSharp examples for Reflection:Type

Introduction

Useful Methods from the System.Dynamic.DynamicObject Class

Method Description
TryBinaryOperation Called for binary operations such as addition and multiplication
TryConvert Called for operations that convert from one type to another
TryCreateInstance Called when the type is instantiated
TryGetIndexCalled when a value is requested via an array-style index
TryGetMember Called when a value is requested via a property
TryInvokeMemberCalled when a method is invoked
TrySetIndexCalled when a value is set via an array-style index
TrySetMember Called when a property value is set

Demo Code


using System;// www  .  ja v  a  2 s .c o m
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Dynamic;

class MainClass
{
    static void Main(string[] args)
    {
        dynamic dynamicDict = new MyDynamicDictionary();
        // set some properties
        Console.WriteLine("Setting property values");
        dynamicDict.FirstName = "A";
        dynamicDict.LastName = "L";

        // get some properties
        Console.WriteLine("\nGetting property values");
        Console.WriteLine("Firstname {0}", dynamicDict.FirstName);
        Console.WriteLine("Lastname {0}", dynamicDict.LastName);

        // call an implemented member
        Console.WriteLine("\nGetting a static property");
        Console.WriteLine("Count {0}", dynamicDict.Count);

        Console.WriteLine("\nGetting a non-existent property");
        try
        {
            Console.WriteLine("City {0}", dynamicDict.City);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
        {
            Console.WriteLine("Caught exception");
        }
    }
}
class MyDynamicDictionary : DynamicObject
{
    private IDictionary<string, object> dict = new Dictionary<string, object>();

    public int Count
    {
        get
        {
            Console.WriteLine("Get request for Count property");
            return dict.Count;
        }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        Console.WriteLine("Get request for {0}", binder.Name);
        return dict.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        Console.WriteLine("Set request for {0}, value {1}", binder.Name, value);
        dict[binder.Name] = value;
        return true;
    }


}

Related Tutorials