Implementing Method_Missing in C#

Heart of the ruby on rails magic in creating a very expressive and eloquent web development framework is the use of ruby’s method_missing.

Following is an example of method_missing in action :

class Roman
  def romanToInt(str)
    # ...
  def method_missing(methId)
    str = methId.id2name


r =

Following is a C# 4.0 equivalent using the dynamic keyword.

using System;
using System.Dynamic;
namespace Vitraag.MetaProgramming
    class Program
        static void Main(string[] args)
            dynamic Caesar = new Roman();

    class Roman: DynamicObject
        int StringToRoman(string s)
            // Simple logic needs a better function
            switch (s)
                case "I" : return 1;
                case "IV": return 4;
                // Should add more cases
                default: return 0;

        public override bool TryGetMember(GetMemberBinder binder,
             out object result)
            result = StringToRoman(binder.Name);
            // This logic could be improved
            if ((int)result != 0)
                return true;
            return false;

Running the above code gives us the result as: 4

I’ll be adding more thoughts in coming weeks around meta-programming and having an extensible type and formatting system. Please feel free to share your best reads or comments on the topic below!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s