1

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)

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
kofifus
  • 17,260
  • 17
  • 99
  • 173
  • 2
    Firstly, there are setting to monitor for exceptions types and you can just turn them off, however, the fact you are using exceptions to control the flow of your application is the real problem here, although this can work, it is bad design... You really should be in control of this, you know your types, or if dont you could use reflection to figure it out, either way its a bit smelly – TheGeneral Aug 22 '18 at 23:18
  • ah got it, I should look for a constructor using Type.GetConstructor ! if you want to post an answer I'll mark it, thanks! – kofifus Aug 22 '18 at 23:28
  • 1
    I think the real question here is _why you are using `Activator.CreateInstance` for a type you **know** at **compile-time**?_ Why not just use `new MyClass(f1, f2)`? –  Aug 23 '18 at 00:18
  • Also, to _"to prevent the debugger from stopping on the exception if it is caught"_ - see https://stackoverflow.com/a/34172404/585968 –  Aug 23 '18 at 00:21

1 Answers1

3

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

TheGeneral
  • 79,002
  • 9
  • 103
  • 141