title: How to check a type for parameterless constructor?
body: <p>Because I want to avoid an exception, I want to check whether a type has a parameterless constructor. How can I achieve this?</p>
  
  <p>I need something like this:</p>
  
  <pre><code>bool HasDefaultConstructor&lt;TT&gt;(TT source)
  {
     return ???;
  }
  </code></pre>
  
  <p>EDIT:
  I want to create an object of same type as source and if it hasn't a default constructor I want to use default(TT) instead.</p>
  
  <p>What I have right now is:</p>
  
  <pre><code>        static TT CreateObject&lt;TT&gt;(TT source)
      {
          try
          {
              if(!HasDefaultConstructor&lt;TT&gt;(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&lt;TT&gt;(TT source)
      {
          ConstructorInfo c = typeof(TT).GetConstructor(new Type[] { });
  
          return c != null;
      }
  </code></pre>
  
  <p>But the check gives me true and CreateInstance throws exception</p>
  
  <blockquote>
    <p>No parameterless constructor</p>
  </blockquote>
  
  <p>Solution:</p>
  
  <pre><code>bool HasDefaultConstructor(Type t)
  {
     return t.GetConstructor(Type.EmptyTypes) != null;
  }
  </code></pre>
  
  <p>There were many recursive functions and iterations involved and somewhere down this way, the wrong generic function HasDefaultConstructor (with type object) has been called. Using a non generic function did the trick.</p>
  
  <p>Thank you all for your constructive help.</p>