Reputation: 2741
How do you easily clone (copy) a RectangleF
in C#?
There are obviously inelegant ways to do it, such as new RectangleF(r.Location, r.size)
, but surely there's a .Copy
or .Clone
method hiding somewhere? But neither of those compiles for me, nor does there appear to be a copy constructor. I suspect there's some simple, C#-standard way of copying any struct, that I just haven't found yet.
In case it matters, my real objective is to make a method that returns an offset version of a rectangle (because, amazingly, RectangleF
doesn't have such built in - it has only a mutator method). My best stab at this is:
public static RectangleF Offset(RectangleF r, PointF offset) {
PointF oldLoc = r.Location;
return new RectangleF(new PointF(oldLoc.X+offset.X, oldLoc.Y+offset.Y), r.Size);
}
(Made uglier than it should by be the astounding lack of an addition operator for PointF
, but that's another issue.) Is there a simpler way to do this?
Upvotes: 2
Views: 2343
Reputation: 410
RectangleF is a struct i.e. a value type. Consider the following:
public class Program
{
struct S
{
public int i;
}
static void Main(string[] args)
{
S s1 = new S();
S s2 = s1;
s1.i = 5;
Console.WriteLine(s1.i);
Console.WriteLine(s2.i);
}
}
The output is:
5
0
Because S is a struct i.e. s2 is a copy of s1.
Upvotes: 7
Reputation:
A Rect
is a struct, a value type.
To clone it just assign it to a new variable.
Upvotes: 4