C# 4.0, detect if a method is missing


I have a situation where i want to add LinePragmas to CodeDom objects. But some code dom objects have the LinePragma property and some don't.

So I'm wondering if it's possible to use the dynamic keyword to detect if the property exists on the object (without throwing an exception) and if it does then add the pragma. Here is my current method:

public static T SetSource<T>(this T codeObject, INode sourceNode)
    where T : CodeObject
    codeObject.UserData["Node"] = sourceNode.Source;
    dynamic dynamicCodeObject = codeObject;

    // How can I not throw an exception here?
    if (dynamicCodeObject.LinePragma != null)
        dynamicCodeObject.LinePragma = new CodeLinePragma(

    return codeObject;

The solution I went with was to add an extension method called Exists(). I wrote a blog post about it here:
Member Exists Dynamic C# 4.0

The jist was to create an extension method that returns an object that implements DynamicObject's TryGetMember. It uses reflection to then return true or false. Which allows you to write code like this:

object instance = new { Foo = "Hello World!" };
if (instance.Reflection().Exists().Foo)
    string value = instance.Reflection().Call().Foo;

Best Solution

You can detect if an object has a property without having to use the dynamic features of C# 4.0 - instead using the reflection features that have been around for a while (I know at least .NET 2.0, not sure about < 2.0)

PropertyInfo info = codeObject.getType().GetProperty(
    BindingFlags.Public | BindingFlags.Instance

If it the object does not have the property, then GetProperty() will return null. You can do similar for fields ( GetField() ) and methods ( GetMethod() ).

Not only that, but once you have the PropertyInfo, you can use it directly to do your set:

info.SetValue(codeObject, new CodeLinePragma(), null);

If you're not sure whether the property has a set method, you could take the even safer route:

MethodInfo method = info.GetSetMethod();
if(method != null)
    method.Invoke(codeObject, new object[]{ new CodeLinePragma() });

This also gives you the added benefit of being a little more performant over the lookup overhead of the dynamic call (can't find a reference for that statement, so I'll just float it out there).

I suppose that doesn't answer your question directly, but rather is an alternative solution to accomplish the same goal. I haven't actually used #4.0 features yet (even though I'm a huge fan of the dynamic typing available in Ruby). It certainly not as clean/readable as the dynamic solution, but if you don't want to throw an exception it may be the way to go.

EDIT: as @arbiter points out, "This is valid only for native .net dynamic objects. This will not work for example for IDispatch."