title: “where this : class” wrong syntax
body: <pre><code>public static class Extensions
  {
      public static T TryCast&lt;T&gt;(this object parent)
          where T : class
          where this : class
      {
          T child = (T)Activator.CreateInstance(typeof(T));
          foreach (PropertyInfo prop in parent.GetType().GetProperties())
          {
              child.GetType().GetProperty(prop.Name)?.SetValue(child, prop.GetValue(parent));
          }
  
          return child;
      }
  }
  </code></pre>
  
  <p>TryCast can be used as:</p>
  
  <blockquote>
    <p>someString.TryCast&lt; someClassToCastTo >()</p>
  </blockquote>
  
  <p>but it is not constrained to only classes, as "where this : class" returns syntax error", which means that, without the "this : class" constriction, it will appear on variables like int, char, etc. </p>
  
  <p>I am searching for a way to constrain the type "this object parent" to only class variables, as in my use case it would make no sense to use it on simple types like int and char.</p>
  
  <p><strong>Note:</strong></p>
  
  <p>It is possible to capture and restrict the parent's type like so:</p>
  
  <pre><code>public static T2 TryCastWorse&lt;T, T2&gt;(this T parent)
      where T : class
      where T2 : class
  {
      T2 child = (T2)Activator.CreateInstance(typeof(T2));
      foreach (PropertyInfo prop in parent.GetType().GetProperties())
      {
          child.GetType().GetProperty(prop.Name)?.SetValue(child, prop.GetValue(parent));
      }
  
      return child;
  }
  </code></pre>
  
  <p>And then use it like so:</p>
  
  <blockquote>
    <p>someString.TryCastWorse&lt; string, someClassToCastTo >()</p>
  </blockquote>
  
  <p>This is not optimal, as one has to specify the class of the calling variable, as observed in the first type in the &lt;>, which is a string, which should be always equal to someString.</p>
  
  <p>This is not intended functionality in this case as it can introduce errors in some use cases.</p>