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.

Rectangle.Center Property

myRectangle.Center returns a Point

Share:
14,256

Related videos on Youtube

Benny
Author by

Benny

i love c# and doing programming on .net

Updated on May 29, 2020

Comments

  • Benny
    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
      I. J. Kennedy over 13 years
      I find this to be a strange omission as well.
  • CallMeLaNN
    CallMeLaNN about 13 years
    How to add this extension to System.Drawing.Rectangle?
  • Jon Skeet
    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
    Stobor over 12 years
    connect.microsoft.com/VisualStudio/feedback/details/93879/… is where it has been suggested formally.
  • Benny
    Benny almost 10 years
    in which version? .net 5?
  • Evorlor
    Evorlor almost 10 years
    4.5.51641 has it. Not sure when it was added.
  • Jon Skeet
    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 different Rectangle type, or did I miss something?
  • Jon Skeet
    Jon Skeet almost 10 years
    Which exact type are you referring to? A link would be useful.
  • Evorlor
    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/…

Related