title: How to cast to a type in C#
body: <p>Can anyone explain how to get this to work?  I am passing in the type name, and "t" is being correctly populated.  I just cannot figure out how to cast objectToCast to type "t".  Any help is appreciated.</p>
  
  <pre><code>....
  Type t = Type.GetType("castToTypeNameHere");
  o = CastTo&lt;t&gt;(objectToCast);
  ....
  
  private T CastTo&lt;T&gt;(Object obj)
  {
      return (T)obj;
  }
  </code></pre>
  
  <p>FYI, here's the answer I found:</p>
  
  <pre><code>Type t = Type.GetType(element.Attribute("castToType").Value);
  MethodInfo castMethod = this.GetType().GetMethod("CastTo", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(t);
  object castedObject = castMethod.Invoke(this, new object[] { objectToCast });
  </code></pre>