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)
    # ...
  end
  def method_missing(methId)
    str = methId.id2name
    romanToInt(str)
  end
end

Results:

r = Roman.new
r.iv
»
4
r.xxiii
»
23
r.mm

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();
            Console.WriteLine(Caesar.IV);
            Console.ReadKey();
        }
    }

    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!

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment