views:

189

answers:

1

Is there a tool that will auto-indent code that uses object initializers in the following manner:

SomeType someType = new SomeType
{
    Prop1 = "prop 1 value",
    Prop2 = "prop 2 value",
    Things = new List<Thing>
    {
        new Thing
        {
            ThingProp = "thing prop value"
        }
    }
};

i.e. using the same brace indenting rules as are commonly seen in other C# code.

ReSharper likes to indent more heavily but then won't maintain the intentation if the code changes later on (we have turned off various ReSharper options to prevent this from happening).

The standard Visual Studio 2008 formatting option (Ctrl-K-D) doesn't change the indentation of object initializers.

Class definitions are included below

public class Thing
{
    public string ThingProp { get; set; }
}

public class SomeType
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public List<Thing> Things { get; set; }
}
+2  A: 

Go into ReSharper / Options / Languages / C# / Formatting Style / Other and uncheck "Indent array, object and collection initializer block" (near the bottom).

(There are a few different options to do with arrays, collection and object initializers, but they're scattered through the different sections. As far as I can tell, the preview doesn't take the other options you've got selected into account, which doesn't help...

EDIT: If you get ReSharper to reformat the code using Ctrl-E Ctrl-C you can get it to format the code exactly as per your post. To make the embedded list item expand fully, you need to untick "Place simple array, object and collection on single line" in Line Breaks and Wrapping though - and that may not be what you want elsewhere :(

Jon Skeet
That stops ReSharper from meddling with the formatting, but sadly doesn't help with auto-formatting
Richard Ev
Really? For me it made the autoformatting just work as I expected it to. When you hit }, what does it do?
Jon Skeet
My initial comment wasn't 100% correct - this works, but not for the `List<Thing>` initialization
Richard Ev
Okay, I'll try to reproduce the exact situation and fiddle with the options some more.
Jon Skeet
It looks like the auto-formatting fails when it hits any property that is a reference type that also uses object initialization in the same statement.Note that it formats correctly while you type, but not if you are trying to re-format code that is badly indented.
Richard Ev
How are you trying to reformat? I usually just remove the retype the last closing brace.
Jon Skeet
I have tried both retyping the closing semicolon and Ctrl-K-D. In both scenarios the reformatting fails for everything after the `new List<Thing>` in my posted example
Richard Ev