toddmo toddmo - 4 years ago 79
C# Question

Is it possible to use an initializer on a function return value?

I'd like to do:

var myClassInstance = myFactory.CreateMyClass() { MyPropertyA = "blah", MyPropertyB = "Bleh"};

but the compiler doesn't like that.

Is there away around this? I'm trying to avoid:

var myClassInstance = myFactory.CreateMyClass();
myClassInstance.MyPropertyA = "blah";
myClassInstance.MyPropertyB = "Bleh";

I know I said
, but it isn't mine. I can't change


Based on David Culp's answer, I made this extension function:

public static object With(this object obj, object additionalProperties)
var type = additionalProperties.GetType();
foreach (var sourceField in type.GetFields())
var name = sourceField.Name;
var value = sourceField.GetValue(additionalProperties);
if (type.GetMember(name)[0] is FieldInfo)
type.GetField(name).SetValue(obj, value);
type.GetProperty(name).SetValue(obj, value);
return obj;

and it's used like this:

var myClassInstance = myFactory.CreateMyClass().With(new { MyPropertyA = "blah", MyPropertyB = "bleh"});

Answer Source

While it isn't possible to do exactly what you are asking, you can use the Builder design pattern to increase readability.

Something along these lines:

var myClassInstance = myFactory.CreateMyClass()

This can be done with either extension methods or wrapping myFactory in a builder class of your own.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download