Note: When is a reference a copy?
In C#, often I find it easier to reference objects by a shorthand than to call the exact place I need it from, such as the case of:
Circle c = circles[i];
someValue = c.getNumber()
c.callMethod();
However, what happens when you actually want to copy the obhect entirely, in the same vein as int i = j;?
All primitive data types copy when using = by default, whereas complex data types such as objects will reference instead. In the case of objects, in order to create an entirely new duplicate object you would call a copy() function (or at the very least something that fulfills the same role) that effectively creates a new object and assigns all of its primitive values to be the same as the object it is copying. The following would print out "objects are different".
Circle c = circles[i].copy();
if (c == circles[i])
{
Console.WriteLine("objects are the same");
}
else
{
Console.WriteLine("objects are different");
}
And for the fun of it, the same in Java:
String notCSharp = new String(arrayStrings[i]);
if (notCSharp == arrayStrings[i])
{
System.out.print("objects are the same");
}
else
{
System.out.print("objects are different");
}
And that's about that.
Circle c = circles[i];
someValue = c.getNumber()
c.callMethod();
However, what happens when you actually want to copy the obhect entirely, in the same vein as int i = j;?
![]() |
Before doing this, understand that ^. Object =/= values, they are unique. |
Circle c = circles[i].copy();
if (c == circles[i])
{
Console.WriteLine("objects are the same");
}
else
{
Console.WriteLine("objects are different");
}
And for the fun of it, the same in Java:
String notCSharp = new String(arrayStrings[i]);
if (notCSharp == arrayStrings[i])
{
System.out.print("objects are the same");
}
else
{
System.out.print("objects are different");
}
And that's about that.
Subscribe to:
Posts (Atom)