why there is no Center() method for Rectangle class in c#?
14,256
Solution 1
Presumably it wasn't deemed useful enough to merit inclusion.
You could easily add it as an extension method if you want though (and if you're using C# 3):
public static Point Center(this Rectangle rect)
{
return new Point(rect.Left + rect.Width/2,
rect.Top + rect.Height / 2);
}
Note that as the values are expressed as integers, you could easily end up getting a non-exact value, assuming you want to return a Point
rather than another structure using decimal
or double
.
The above is actually for the System.Drawing.Rectangle
struct. If you're talking about a different Rectangle, please add the appropriate information and I'll edit my answer.
Solution 2
It exists within the (no longer supported) Microsoft.XNA.Framework.
myRectangle.Center
returns a Point
Related videos on Youtube
Comments
-
Benny almost 4 years
previously, there is such method for Rectangle in MFC, i dont know why there is not for the c# version.
-
I. J. Kennedy over 13 yearsI find this to be a strange omission as well.
-
-
CallMeLaNN about 13 yearsHow to add this extension to System.Drawing.Rectangle?
-
Jon Skeet about 13 years@CallMeLaNN: Just declare it in a static, non-generic, top-level class. For more details, read up about extension methods in general, e.g. in MSDN.
-
Stobor over 12 yearsconnect.microsoft.com/VisualStudio/feedback/details/93879/… is where it has been suggested formally.
-
Benny almost 10 yearsin which version? .net 5?
-
Evorlor almost 10 years4.5.51641 has it. Not sure when it was added.
-
Jon Skeet almost 10 years@Evorlor: There still isn't in
System.Drawing.Rectangle
as far as I can see. Were you thinking of a differentRectangle
type, or did I miss something? -
Jon Skeet almost 10 yearsWhich exact type are you referring to? A link would be useful.
-
Evorlor almost 10 years@Jon Skeet Eep! I was using Microsoft.Xna.Framework (which I think is no longer supported). My mistake! msdn.microsoft.com/en-us/library/…