Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing indentation when object initializers have been used

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; }
}
like image 990
Richard Ev Avatar asked Oct 26 '09 11:10

Richard Ev


1 Answers

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...)

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. :(

like image 61
Jon Skeet Avatar answered Oct 22 '22 18:10

Jon Skeet