Better formatting for collection initializers with Resharper

January 3, 2010 21:42

By default, formatting for collection initializers doesn't look really neat with Resharper.

Just type some initializers or paste them from another place
or reformat existing code - and here's something you will probably get:

var hmm = new NewYearHangover
            {
                Year = 2010,
                Place = new Place
                        {
                            Latitude = "40º 55' N",
                            Longitude = "21º 00' E"
                        },
                Memories = new Memories
                           {
                               Conversations = new[]
                                               {
                                                   "Philosophy", "Aviation", "Children"
                                               },
                               Fun = true
                           }
            };


However, you can easily make it less space-consuming. How about this:


var hmm = new NewYearHangover {
    Year = 2010,
    Place = new Place {
        Latitude = "40º 55' N",
        Longitude = "21º 00' E"
    },
    Memories = new Memories {
        Conversations = new[] {
            "Philosophy", "Aviation", "Children"
        },
        Fun = true
    }
};


If you like the second one more, here's how you can do it:

  1. Goto Resharper | Options | C# | Formatting Style
  2. Under Braces Layout, make sure you have
    • Array and object initializer set to "End of line (K&R style)"
  3. Under Other, make sure you have
    • Align Multiline Constructs | Array, object and collection initializer unchecked
    • Other | Indent array, object and collection initializer block  unchecked

Once you do that, Resharper will be able to format your collection initializers accordingly.

Have fun and Happy New Year!

Comments

Add comment


 

  Country flag

b    i    u    quote    

  • Comment
  • Preview
Loading