Search code examples
c#objectfactoryinitializer

Is it possible to use a c# object initializer with a factory method?


I have a class with a static factory method on it. I want to call the factory to retrieve an instance of the class, and then do additional initialization, preferablly via c# object initializer syntax :

MyClass instance = MyClass.FactoryCreate()
{
  someProperty = someValue;
}

vs

MyClass instance = MyClass.FactoryCreate();
instance.someProperty = someValue;

Solution

  • Yes. You can use object initializer for already created instance with the following trick. You should create a simple object wrapper:

    public struct ObjectIniter<TObject>
    {
        public ObjectIniter(TObject obj)
        {
            Obj = obj;
        }
    
        public TObject Obj { get; }
    }
    

    And now you can use it like this to initialize your objects:

    new ObjectIniter<MyClass>(existingInstance)
    {
        Obj =
        {
            //Object initializer of MyClass:
            Property1 = value1,
            Property2 = value2,
            //...
        }
    };
    

    P.S. Related discussion in dotnet repository: https://github.com/dotnet/csharplang/issues/803