Search code examples
c#system.reflectionc#-7.0

Visual Studio 2017 prevent debugger from stopping on exception in Activator.CreateInstance


I have code that tries to create an object first with one constructor and then, if that fails, with the default constructor:

MyClass Construct(MyField f1, MyField f2) 
{
    try 
    {
        return (MyClass)Activator.CreateInstance(typeof(MyClass), f1, f2);
    }
    catch 
    {
        var o = (MyClass)Activator.CreateInstance(typeof(MyClass)); 
        o.f1= f1; 
        o.f2=f2;
        return o;
    }
}

I want to prevent the debugger from stopping on the exception if it is caught. I tried [DebuggerStepThrough], [DebuggerHidden] and [DebuggerNonUserCode] without luck.

I also tried running: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VsRegEdit.exe" set "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community" HKLM Debugger\Engine AlwaysEnableExceptionCallbacksOutsideMyCode dword 1 as advised here but no luck.

Is there any way to do this in VS2017? Alternatively, is there a way to use Activator.CreateInstance that will return null instead of throwing an exception?

(using visual studio 2017 15.8.0 preview 4.0)


Solution

  • A quick an nasty approach is to look for constructors, GetConstructors and looking at the GetParameters count, then branch accordingly.

    var ctors = typeof(A).GetConstructors();
    // assuming class A has only one constructor
    var ctor = ctors[0];
    foreach (var param in ctor.GetParameters())
    {
        Console.WriteLine(string.Format(
            "Param {0} is named {1} and is of type {2}",
            param.Position, param.Name, param.ParameterType));
    }
    

    Once again, there are probably better ways to do this. However, at least you aren't using exceptions to control the flow of your application.

    If you know the type of your classes, you could also compare types. Or if you are using base classes, or interface, you could use generics with constraints. A lot of this depends on the stuff we cant see and the whys