Generic type checking and method invocation -- generically!

by timvasil 11/8/2007 5:02:00 PM

Determining whether an object implements the generic version of IDictionary isn't as easy as it seems.  Ideally this would work:

o is IDictionary<,>

Unfortunately, it doesn't.  Leaving out type parameters (i.e. "<,>") is supported only with the typeof operator.

So, after some experimentation, here's how you can do that type of test, and then invoke a generic method with type parameters:

    class Program
    {
        private static readonly MethodInfo _doStuffMethod = typeof(Program).GetMethod("DoStuff");

        static void Main()
        {
            Dictionary<string, int> map = new Dictionary<string, int>();
            Encode(map);
        }

        static void Encode(object val)
        {
            if (val is IEnumerable)
            {
                Type valType = val.GetType();
                if (valType.IsGenericType)
                {
                    foreach (Type valInterface in valType.GetInterfaces())
                    {
                        if (valInterface.IsGenericType && typeof(IDictionary<,>).IsAssignableFrom(valInterface.GetGenericTypeDefinition()))
                        {
                            Type[] valTypeParams = valInterface.GetGenericArguments();
                            _doStuffMethod.MakeGenericMethod(valTypeParams[0], valTypeParams[1]).Invoke(null, new object[] { val });
                        }
                    }
                }
            }
        }

        public static void DoStuff<K, V>(IDictionary<K, V> dic)
        {
            Console.WriteLine(dic.ToString());
        }
    }

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C#

Related posts

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments