Reputation: 41
I want to add additional values to a rectangle. Like a "Name" string for example.
Something like this:
Rectangle MyRectangle = new Rectangle(Y, X, Width, Height, Name)
Is this possible?
Upvotes: 1
Views: 1055
Reputation: 46239
There is two overload constructor function in Rectangle class.
public Rectangle(Point location, Size size);
public Rectangle(int x, int y, int width, int height);
But there isn't a constructor function parameter new Rectangle([int], [int], [int], [int], [string])
in Rectangle
class.
You can try to use composite public Rectangle rect { get; set; }
property in the class.
Then use constructor function to set Rectangle
object and Name
public class CustomerRectangle
{
public Rectangle Rect { get; set; }
public string Name { get; set; }
public CustomerRectangle(int llx, int lly, int urx, int ury,string name)
{
Rect = new Rectangle(llx, lly, urx, ury);
Name = name;
}
}
then you can use
CustomerRectangle MyRectangle = new CustomerRectangle (Y, X, Width, Height, Name);
//MyRectangle.Name; use Name property
//MyRectangle.Rect; use Rectangle
Upvotes: 1
Reputation: 657
I've seen others have contributed good examples, but in case of Cannot inherit from sealed type
error, following example might help you:
public class myRectangle
{
private Rectangle newRectangle = new Rectangle();
private string name;
public myRectangle Rectangle(Int32 Y, Int32 X, Int32 Height, Int32 Width, string name )
{
newRectangle.Y = Y;
newRectangle.X = X;
newRectangle.Height = Height;
newRectangle.Width = Width;
this.name = name;
return this;
}
}
Upvotes: 0
Reputation: 547
I assume you are using a constructor from the System.Drawing namespace: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.rectangle?view=netframework-4.7.2
It is not possible to add an extra field to that structure. What you can do is create your own class or structure which does contain more .
public class NamedRectangle
{
public string Name { get; set; }
public double X { get; set; }
public double Y { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public NamedRectangle(double x, double y, double width, double height, string name)
{
Name = name;
X = x;
Y = y;
Width = width;
Height = height;
}
}
Upvotes: 1