[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make rectangle extension methods in C#

[Make rectangle extension methods in C#]

This example shows how to add rectangle extension methods to the Rectangle and RectangleF structs.

The Rectangle and RectangleF structs have several useful properties for determining their geometry such as Left, Right, Top, and Bottom, but they have no midpoint properties. The following code adds MidX and MidY methods to these structs so your code can easily find midpoint values.

public static class RectangleExtensions { public static int MidX(this Rectangle rect) { return rect.Left + rect.Width / 2; } public static int MidY(this Rectangle rect) { return rect.Top + rect.Height / 2; } public static Point Center(this Rectangle rect) { return new Point(rect.MidX(), rect.MidY()); } public static float MidX(this RectangleF rect) { return rect.Left + rect.Width / 2; } public static float MidY(this RectangleF rect) { return rect.Top + rect.Height / 2; } public static PointF Center(this RectangleF rect) { return new PointF(rect.MidX(), rect.MidY()); } }

These methods are contained in the static RectangleExtensions class. They simply calculate the X and Y midpoint coordinates and return them. The Center methods return Point and PointF values giving the rectangles' centers.

You could easily perform these calculations when you need them, but putting them in extension methods makes them a little easier to use and makes your code easier to read. The following code shows how the program's Paint event handler draws the shapes shown in the picture.

private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle(10, 10, ClientSize.Width - 20, ClientSize.Height - 20); e.Graphics.DrawRectangle(Pens.Red, rect); PointF[] points = { new PointF(rect.MidX(), rect.Y), new PointF(rect.Right, rect.MidY()), new PointF(rect.MidX(), rect.Bottom), new PointF(rect.Left, rect.MidY()), }; e.Graphics.DrawPolygon(Pens.Blue, points); e.Graphics.DrawLine(Pens.Green, rect.Center(), new PointF(0, 0)); }

The code creates a RectangleF struct and draws it. It then uses the struct's MidX, MidY, and Center extension methods to draw the blue diamond and the green line.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.