Using Reflection to Choose a Method at Runtime

5 07 2011

An area in our code is charged with serializing a given object to a given BinaryWriter. Most of the time the object is a primitive type that requires just figuring out what type it is, casting it and calling the appropriate Write() method on the BinaryWriter. The obvious solution is a big if statement checking the object’s type and forwarding the casted object to Write(). This approach is a bit of a pain because the method becomes big and a pain to maintain, it’s also frustrating to look at a lot of code that is basically the same repeated over and over.

I tried a different approach using the reflection classes and a little Linq. The resulting method is small and covers all the primitive types in one go. This approach is probably slower than the if-else one (I’ll profile it later) but the reduced code size and increased maintainability make it a good option.

static void Serialize(Object obj, BinaryWriter writer)
    var objRunTimeType = obj.GetType();
    var binaryWriterType = typeof(BinaryWriter);

    var writeMethod = (from m in binaryWriterType.GetMethods()
                       where m.Name == "Write" && m.GetParameters()[0].ParameterType == objRunTimeType
                       select m).First();

    writeMethod.Invoke(writer, new object[] {obj});



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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: