JKreft
JKreft

Reputation: 113

Add a Constructor to a C# System Class

I want to add an additional copy constructor to the System.Drawing.RectangleF class that would take another RectangleF as its sole parameter.

I tried making a partial class in the System.Drawing namespace and it gave me a namespace collision. I tried just making it using an extension class, and it won't treat it as a constructor.

Upvotes: 0

Views: 213

Answers (2)

whatsisname
whatsisname

Reputation: 6140

In the case of RectangleF, you don't have to actually do anything, because RectangleF is a struct, and so it has value semantics. Assigning the Rect to a variable copies its contents.

Take the following example code:

RectangleF a = new RectangleF(1, 2, 3, 4);
Console.WriteLine(a);
RectangleF b = a;   //a gets copied to b
Console.WriteLine(b);
a.X = 5;
a.Y = 6;
a.Width = 7;
a.Height = 8;
Console.WriteLine(a);
Console.WriteLine(b);

And when you run it, you'll get the following output:

{X=1,Y=2,Width=3,Height=4}
{X=1,Y=2,Width=3,Height=4}
{X=5,Y=6,Width=7,Height=8}
{X=1,Y=2,Width=3,Height=4}

You can see the value of a is copied to b, and then b stays unchanged when you modify a. If RectangleF was an actual class, it would have reference semantics and the last two lines of output would be the same thing.

Upvotes: 3

Erik Eidt
Erik Eidt

Reputation: 26636

I think you can only use the partial class feature if you effectively own the class. That is you can't partial a class in another DLL as is the case here.

The RectangleF is a struct, btw, not a class, not that this really changes anything.

You might look into extension methods; you wouldn't be able to define a constructor, but you could define an extension method that let's you do:

var newRectangleF = existingRectangleF.clone ();

Extension methods can be defined across DLL boundaries, and can invoked using instance method syntax or a static method syntax. They work nicely with Visual Studio, such as in completion suggestions.


You also might find MemberwiseClone() interesting.

Upvotes: 1

Related Questions