Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use either <code>Activator.CreateInstance&lt;T&gt;()</code> or invoke the constructor via <code>typeof(T).GetConstructor(...).Invoke(new object[] { ... });</code></p> <p>If you need alot of this operations; you can also use <code>Expression.New</code> to create them; as <code>CreateInstance</code> and via the constructor are quite expensive methods.</p> <hr> <p>Example of doing it the Expression based way.</p> <pre><code> private void Foo() { TestJan myObject = CreateObject&lt;TestJan&gt;("Jan", 21); } private T CreateObject&lt;T&gt;(string name, int age) { //first get a reference to the ConstructorInfo //we know constructor has 2 params, string and int32. Names are not important. System.Reflection.ConstructorInfo ci = typeof(T).GetConstructor(new[] { typeof(string), typeof(int) }); //we now have to define the types ParameterExpression stringParam = Expression.Parameter(typeof(string), "stringExp"); ParameterExpression intParam = Expression.Parameter(typeof(int), "intExp"); //create an expression NewExpression constructor = Expression.New(ci, stringParam, intParam); //wrap this in a lambda-expression, which returns basically // (stringExp, intExp) =&gt; new T(stringExp, intExp); LambdaExpression lambda = Expression.Lambda(constructor, stringParam, intParam); //compile into delegate var constructorDelegate = (Func&lt;string, int, T&gt;)lambda.Compile(); //invoke the delegate. Normally you would cache this in a static Dictionary&lt;Type, Delegate&gt;. //when you cache this, it's lightning fast. As it's just as fast as hard program // (stringExp, intExp) =&gt; new T(stringExp, intExp); return constructorDelegate.Invoke(name, age); } </code></pre> <p>You can vary of course with the parameters and such, I find this the way best way to create an object, because it's both fast and flexible.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload