How to check type for constructor without parameters?

Since I want to avoid an exception, I want to check if the type has a constructor without parameters. How can I achieve this?

I need something like this:

bool HasDefaultConstructor<TT>(TT source) { return ???; } 

EDIT: I want to create an object of the same type as the source, and if it does not have a default constructor, I want to use the default value (TT) instead.

What I have now:

  static TT CreateObject<TT>(TT source) { try { if(!HasDefaultConstructor<TT>(source)) { return default(TT); } return (TT)Activator.CreateInstance(source.GetType()); } catch(Exception ex) { Trace.WriteLine("Exception catched!\r\n" + ex); } return default(TT); } static bool HasDefaultConstructor<TT>(TT source) { ConstructorInfo c = typeof(TT).GetConstructor(new Type[] { }); return c != null; } 

But the check gives me true and the CreateInstance exception throws me

Without parametric constructor

Decision:

 bool HasDefaultConstructor(Type t) { return t.GetConstructor(Type.EmptyTypes) != null; } 

There were many recursive functions and iterations, and somewhere like that, the wrong general HasDefaultConstructor function (with an object of type) was called. Using a non-generic function did the trick.

Thank you all for your constructive help.

+5
source share
2 answers

GetConstructor(Type.EmptyTypes) will return a constructor without parameters or null if it does not exist, so you can:

 return typeof(TT).GetConstructor(Type.EmptyTypes) != null; 

EDIT

I assume your problem is that TT and source.GetType() are actually two different types. source.GetType() probably comes from TT , but does not have a constructor without parameters. So what you really need to do is check on source.GetType() :

 bool HasDefaultConstructor(Type t) { return t.GetConstructor(Type.EmptyTypes) != null; } if(!HasDefaultConstructor(source.GetType())) ... 
+9
source

Use reflection to check if the type has a constructor with no parameters. Use Type.GetConstructor :

 bool HasDefaultConstructor<TT>() { ConstructorInfo c = typeof(TT).GetConstructor(new Type[] { }); // A constructor without any types defined: no parameters return c != null; } 

If you just want to instantiate a TT , use the new constraint:

 TT CreateUsingDefaultConstructor<TT>() where TT : new() { return new TT(); } 

Like Jeppe Stig Nielsen , you can use this code to find constructors that are not public . In my opinion, you should use this only as a last resort!

 typeof(TT).GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public , null , new Type[] { } , null ) 
+8
source

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


All Articles