DynamicObject in C# 4.0

Just some fooling around with DynamicObject and friends in C# 4.0:


using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ConsoleApplication1 {
   class DynamicTest : DynamicObject {
      public override bool TryInvokeMember(
            InvokeMemberBinder binder, object[] args,
            out object result) {
         var paramList = new Dictionary<string, object>();
         int i = 0;
         foreach ( object obj in args ) {
            string name = binder.CallInfo.ArgumentNames.Count > i ?
               binder.CallInfo.ArgumentNames[i] : ("param" + i);
            paramList.Add(name, obj);
            i++;
         }
         WriteCall(binder.Name, paramList);
         result = null;
         return true;
      }

      public void WriteCall(string name, Dictionary<string, object> paramList) {
         Console.WriteLine("Executing: {0}", name);
         foreach ( string key in paramList.Keys ) {
            Console.WriteLine("\t{0}: {1}", key, paramList[key]);
         }
      }
   }
   class Program {
      static void Main(string[] args) {
         dynamic cl = new DynamicTest();
         cl.MyMethodCall(count:12, value: "this is a string");
      }
   }
}

Executing it outputs this:

Executing: MyMethodCall
        count: 12
        value: this is a string

Comments (2)

5 Articulos sobre VS2010 | Coded StyleMay 30th, 2009 at 3:36 pm

[...] Restrepo ha escrito 5 excelentes artículos sobre VS2010. Aquí la lista: Installing VS2010 Beta 1 DynamicObject in C# 4.0 InvokePowerShell Activity Problem Consuming WCF Service in BizTalk 2009 Comments on the WF 4.0 [...]

Carl WeisNovember 25th, 2009 at 11:43 pm

Can you email me this color scheme?

Leave a comment

Your comment