The constructor call returned null: what to do?

I have a code that looks like this:

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 (for example, what type of exception to throw) when the method Invokereturns something that is not DirectiveNodeor when it returns null(indicated // ???above).

(A method contract nodeTypewill always describe a subclass DirectiveNode.)

I'm not sure when the call to the constructor will return null, so I'm not sure that I need to handle anything at all, but I still want to be safe and throw an exception if something goes wrong.

+3
source share
1 answer

You need to make sure that nodeTypeis DirectiveNode:

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

, () Activator.CreateInstance , ConstructorInfo . , .

+5

Source: https://habr.com/ru/post/1737631/


All Articles