Reputation: 3451
I understand that these two objects point to the same reference, but I don't want that to be the case, so I am a bit confused on how to prevent one from changing the other. Do I need to declare a band new Car object, for example Car car2 = new Car();
? When I do this resharper tells me it is unnecessary. Here is my code:
void Main()
{
Car car = new Car { Color = "Blue"};
Console.WriteLine(car.Color);
//Do I need Car car2 = new Car();
//car2 = car; //Confused.
Car car2 = car;
Console.WriteLine(car2.Color);
car = Format(car);
Console.WriteLine(car.Color);
Console.WriteLine(car2.Color); //How can I prevent car2 from changing color?
}
// Define other methods and classes here
public class Car
{
public string Color {get;set;}
}
public static Car Format(Car car)
{
car.Color = "Red";
return car;
}
var car2= new Car();
car2 = car;
car = Format(car); //This changes car and car2
Upvotes: 0
Views: 265
Reputation: 273264
When I do this resharper tells me it is unnecessar
Then Resharper would be wrong in this case. But it depends on your exact code.
When you want car1 and car2 to be different colors then they should be different instances. And that does require Car car2 = new Car();
Car is a class is a reference-type.
In your posted code there is only 1 instance, so there can only be one color.
Note that for the same reason your Format method does not need to return anything, the following will do exactly the same:
public static void Format(Car car)
{
car.Color = "Red";
}
Upvotes: 2
Reputation: 311
As you mention, car2 and car refer to the same object. It sounds as if you don't want that, so you will need to create a copy of car and call it car2.
You could define a copy constructor for your Car class:
public Car(Car car)
{
this.Color = car.Color;
}
Then use it like this:
Car car2 = new Car(car);
Upvotes: 1
Reputation: 68687
You can make Car a struct
public struct Car
{
public string Color { get; set; }
}
or make Car ICloneable
or any other of the dozen ways to copy the object so you can easily have another instance. We need to see the code that shows the warning so we could figure out the problem. I'm not seeing the warning.
Upvotes: 0