-1

I want be able to declare variables like this:

public static Rectangle CreateFromArray(this Rectangle self, int[] info)
{
    self.X = info[0];      self.Y = info[1];
    self.Width = info[2];  self.Height = info[3];
    return self;
}

But VS formats it like this:

public static Rectangle CreateFromArray(this Rectangle self,int[] info)
{
    self.X = info[0]; self.Y = info[1];
    self.Width = info[2]; self.Height = info[3];
    return self;
}

I tried all the spacing options in Code Style -> Formatting and didn't find any that work.

  • 2
    IMHO, it would be easier to read, and would look tidier, if they were all on new lines. That's just an opinion, so feel free to ignore it, but I wonder how many people would agree... – Andrew Williamson Jun 17 '18 at 19:37
  • Thanks, but I'm looking for an answer. – user3700697 Jun 17 '18 at 20:05
  • Using a formatting plugin, my compromise workflow is: edit as needed first. Then apply the built-in VS formatting if I made extensive file-wide changes. Then apply plugin formatting. The plug-in is very easy and fast because it applies itself to contiguous lines without highlighting anything. Yes I must apply the plugin commands to each "chunk" of lines but it's so fast it's not a problem. [I used Align](https://marketplace.visualstudio.com/items?itemName=cpmcgrath.Codealignment) – radarbob Jun 17 '18 at 20:18
  • Interesting extension bob, thanks. I was hoping to find a way that wasn't incompatible with VS auto-format, since the changes just get wrecked every time I ctrl+K+D. But I should have known better than to try to do something non-standard in VS, since it usually ends up costing me more time than it will save in my entire career. – user3700697 Jun 17 '18 at 20:41

1 Answers1

1

Since a Rectangle is a struct and therefore a value type, this extension method will not work as expected. The methods gets a copy of the original rectangle and will only change this local copy. The original rectangle you passed as argument will remain unchanged!

Return a new Rectangle instead.

public static Rectangle RectanlgeFromArray(int[] info)
{
    return new Rectangle(info[0], info[1], info[2], info[3]);
}

Note: Since C# 7.2 you can use a ref-Extension method

public static Rectangle CreateFromArray(this ref Rectangle self, int[] info)
...

But since the original rectangle is completely overwritten, it makes no sense to pass it to the method anyway unless you change the return type to void and change it in-place:

public static void FillFromArray(this ref Rectangle self, int[] info)
{
    self.X = info[0]; self.Y = info[1];
    self.Width = info[2]; self.Height = info[3];
}

Usage:

rect.FillFromArray(new int[] { 1, 2, 3, 4 });
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188