Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No. Alternatively you could accept a lambda as an argument, which also gives you full control in which part of the "creation" process will be called. This way you can call it like:</p> <pre><code>MyClass instance = MyClass.FactoryCreate(c=&gt; { c.SomeProperty = something; c.AnotherProperty = somethingElse; }); </code></pre> <p>The create would look similar to:</p> <pre><code>public static MyClass FactoryCreate(Action&lt;MyClass&gt; initalizer) { MyClass myClass = new MyClass(); //do stuff initializer( myClass ); //do more stuff return myClass; } </code></pre> <hr> <p>Another option is to return a builder instead (with an implicit cast operator to MyClass). Which you would call like:</p> <pre><code>MyClass instance = MyClass.FactoryCreate() .WithSomeProperty(something) .WithAnotherProperty(somethingElse); </code></pre> <p>Check <a href="http://elegantcode.com/2008/04/26/test-data-builders-refined/" rel="noreferrer">this</a> for the builder</p> <p>Both of these versions are checked at compile time and have full intellisense support.</p> <hr> <p>A third option that requires a default constructor:</p> <pre><code>//used like: var data = MyClass.FactoryCreate(() =&gt; new Data { Desc = "something", Id = 1 }); //Implemented as: public static MyClass FactoryCreate(Expression&lt;Func&lt;MyClass&gt;&gt; initializer) { var myclass = new MyClass(); ApplyInitializer(myclass, (MemberInitExpression)initializer.Body); return myclass ; } //using this: static void ApplyInitializer(object instance, MemberInitExpression initalizer) { foreach (var bind in initalizer.Bindings.Cast&lt;MemberAssignment&gt;()) { var prop = (PropertyInfo)bind.Member; var value = ((ConstantExpression)bind.Expression).Value; prop.SetValue(instance, value, null); } } </code></pre> <p>Its a middle between checked at compile time and not checked. It does need some work, as it is forcing constant expression on the assignments. I think that anything else are variations of the approaches already in the answers. Remember that you can also use the normal assignments, consider if you really need any of this.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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