Is it possible, in C#, to simplify this if by generalising the properties somehow? Really curious.
Image Crop = new Image("test.jpg");
int Margin = 2;
int Dif = Math.Abs(Crop.Width - Crop.Height);
if (Crop.Width < Crop.Height) {
Crop.X -= Dif / 2; //
Crop.Width += Dif; // A
Dif = Crop.Height * Margin * 2; //
} else {
Crop.Y -= Dif / 2; //
Crop.Height += Dif; // B
Dif = Crop.Width * Margin * 2; //
}
It feels like A & B could be replaced by a function that figured out whether to pick Crops' X & Width, or Crops' Y & Height. The code above works just fine, but I figure that there has to be a prettier way, and I can't find it.
A friend of mine made something, although in Java, using an IntConsumer & lambda functions that managed to simplify A & B into one function that magically works. I don't get it though. :-)
private static int squarize(int n, int shortBound, int longBound, IntConsumer locSetter, IntConsumer boundSetter, int dif, int margin) {
locSetter.accept(n - dif / 2);
boundSetter.accept(shortBound + dif);
return longBound * margin * 2;
}
To answer your question: "Is it possible, in C#, to simplify this if by generalising the properties somehow?":
No, it isn't. Your code is perfectly fine as it is.
Just for completeness, you could do it like this, but to be clear: I don't think this is easier to follow than the original code. It's just "clever".
if (Crop.Width < Crop.Height)
(Crop.X, Crop.Width, Dif) = (Crop.X - Dif / 2, Crop.Width + Dif, Crop.Height * Margin * 2);
else
(Crop.Y, Crop.Height, Dif) = (Crop.Y - Dif / 2, Crop.Height + Dif, Crop.Width * Margin * 2);
Beauty is in the eye of the beholder, so it's up to you if this is "Prettier". ;)
I much prefer the original.