[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: Add an extension method to the Graphics class in C#

[Add an extension method to the Graphics class in C#]

For some strange reason, the Graphics class's DrawRectangle method cannot take a RectangleF as a parameter. It can take a Rectangle or four float values, and the FillRectangle method can take a RectangleF as a parameter, but the DrawRectangle method cannot.

Fortunately it's easy to add this as an overloaded extension method for the Graphics class. The following code shows how the example program does this.

public static class GraphicsExtensions { // Draw a RectangleF. public static void DrawRectangle(this Graphics gr, Pen pen, RectangleF rectf) { gr.DrawRectangle(pen, rectf.Left, rectf.Top, rectf.Width, rectf.Height); } }

Now the program can use the new extension method just as if it had been included in the original class. The following code shows how the example program draws its rectangle.

private void Form1_Paint(object sender, PaintEventArgs e) { // Draw a rectangle. RectangleF rectf = new RectangleF(10, 10, ClientSize.Width - 20, ClientSize.Height - 20); e.Graphics.DrawRectangle(Pens.Red, rectf); }

Omitting this version of DrawRectangle seems like a relatively simple mistake. Fortunately it's easy to fix with an extension method.

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

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