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.
source share