tags:

views:

52

answers:

1

I have code which looks like:

private static DirectiveNode CreateInstance(Type nodeType, DirectiveInfo info) {
    var ctor = nodeType.GetConstructor(new[] { typeof(DirectiveInfo) });

    if(ctor == null) {
        throw new MissingMethodException(nodeType.FullName, "ctor");
    }

    var node = ctor.Invoke(new[] { info }) as DirectiveNode;

    if(node == null) {
        // ???;
    }

    return node;
}

I am looking for what to do (e.g. what type of exception to throw) when the Invoke method returns something which isn't a DirectiveNode or when it returns null (indicated by // ??? above).

(By the method's contract, nodeType will always describe a subclass of DirectiveNode.)

I am not sure when calling a constructor would return null, so I am not sure if I should handle anything at all, but I still want to be on the safe side and throw an exception if something goes wrong.

+5  A: 

You need to ensure that nodeType is a DirectiveNode:

if (!typeof(DirectiveNode).IsAssignableFrom(nodeType))
    throw new ArgumentException("The specified node type is not a 'DirectiveNode'");

Also, you can (should) use Activator.CreateInstance instead of manually finding the ConstructorInfo and invoking it. It's cleaner, more expressive, and more maintainable.

280Z28
Wow, I didn't know about `Activator.CreateInstance`. Thanks. By my contract I'm sure only a `DirectiveNode` subclass is sent to the function, so that wasn't the issue. Anyway, thanks. =]
strager
Are you stopping the debugger and checking? Just because it seems impossible doesn't mean it is impossible.
Snarfblam
The `as` never actually did return `null`. I was asking if I try to should do anything if it did, because it looks like an impossible condition.
strager
@strager: It could return `null` only if the argument is an invalid node type. To answer the question, yes you absolutely should check this condition and throw an `ArgumentException` if it's violated.
280Z28