Frederick Noe Frederick Noe - 1 year ago 133
C# Question

Ambiguous Rectangle constructor

Quick question about the Rectangle constructor in System.Windows.Shapes. I'm trying to create a Rectangle object using the following code.

Rectangle rect1 = new Rectangle(5,5,5,5);

However, I get an error saying that the Rectangle constructor doesn't take 4 arguments. After some extensive research, the documentation gives a couple explicit constructors, such as these two.

Rectangle(int32,int32, int32, int32);


Rectangle(Point, Size);

I have tried using both, and it accepts neither, giving the error that the Rectangle class doesn't accept either 2 or 4 arguments. However, when I don't pass it any arguments, it works fine. The issue is that there is no way to access the location of the Rectangle, so I can only change the width and height after creating the object, not the location.


This is indeed part of a homework assignment, but a very, very small piece of a larger whole, and as I have spent a lot of time on this one simple problem(so I assume), therefore, I have no qualms about asking here.

Answer Source

After some back and forth in comments, this is what you actually want: A UI element in a Canvas, depicting a rectangular shape.

var rect = new System.Windows.Shapes.Rectangle();

//  Capital C Canvas: Static methods of System.Windows.Canvas, setting what are 
//  called "attached properties" in WPF. This is very weird if you're new to WPF, sorry. 
Canvas.SetLeft(rect, 5);
Canvas.SetTop(rect, 5);
rect.Height = 5;
rect.Width = 5;

//  canvas, lowercase c, is your instance of System.Windows.Canvas

With WPF, I prefer to work in XAML rather than C# for creating UI elements:

<Canvas Width="300" Height="300">

Other possible answers, none applicable in this case

If you're in winforms, use System.Drawing.Rectangle instead. That's the one you were reading the documentation for (kudos for actually reading documentation -- few do).

You may possibly have to add to your project a reference to System.Drawing.dll (in References in the project tree in VS).

In WPF, you can use that class, or System.Windows.Rect. That one uses double precision floating point values instead of integers. Pick whichever is appropriate to the task at hand. UI stuff in WPF is all floating point, so Rect may be best.

The one in Shapes is something else.

If System.Windows.Shapes is in your using lines at the top, delete that if you can.

But if you need to keep that, this always works in cases of ambiguity:

var rect = new System.Drawing.Rectangle(5,5,5,5);
var r2 = new System.Windows.Rect(5,5,5,5);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download