Inline object initializer

I'm seeing some odd behavior when attempting to inline a collection into an
object initializer. The method was creating a collection of objects the
old-fashioned way:

MyStuff stuff = new MyStuff();

MyCollection collection = new MyCollection();
collection.Property1 = "foo";
collection.Property2 = "bar";

MyType type = new MyType();
type.Property1 = "foo"
type.Property2 = "bar";
collection.Add(type);

myType = new MyType();
type.Property1 = "foo";
type.Property2 = "bar";
collection.Add(type);

stuff.Add(collection);

It's not nice code, so I decided to refactor it using object initializers
before breaking it apart into something cleaner. The first pas just tackles
adding MyType to MyCollection:

MyStuff stuff = new MyStuff();

MyCollection collection = new MyCollection()
collection.Property1 = "foo";
collection.Property2 = "bar";

collection.Add(new MyType
{
Property1 = "foo";
Property2 = "bar";
});

collection.Add(new MyType
{
Property1 = "foo";
Property2 = "bar";
});

stuff.Add(collection);

In this stage, using ReSharper to convert the constructors and property
setters into object initializers works fine. I then attempt to inline the
collection variable, but ReSharper generates this code for some reason. It
looks like it's just inlining every instance of MyCollection into its own
private property instead of inlining the set into collection.Add(...) as
expected.

MyStuff stuff = new MyStuff();

new MyCollection().Property1 = "foo";
new MyCollection().Property2 = "bar";

new MyCollection.Add(new MyType
{
Property1 = "foo";
Property2 = "bar";
});

new MyCollection.Add(new MyType
{
Property1 = "foo";
Property2 = "bar";
});

stuff.Add(new MyCollection());



Please sign in to leave a comment.