This may be somewhat of a noobish question but I cannot seem to find any information on this behavior at all.
Here is the code:
class Cars
{
public int year = 0;
public string make = " ";
public string model = " ";
public Cars()
{
}
public Cars(int tYear, string tMake, string tModel)
{
year = tYear;
make = tMake;
model = tModel;
}
public string ConvertToString()
{
return year.ToString() + make + model;
}
}
class Program
{
Cars oneCar = new Cars();
List<Cars> manyCars = new List<Cars>();
public void Init()
{
manyCars.Add(new Cars(1993, "Nissan", "240SX"));
manyCars.Add(new Cars(2001, "Isuzu", "Rodeo"));
manyCars.Add(new Cars(2010, "Ford", "F150"));
oneCar = manyCars[2];
oneCar.model = "Pinto";
for (int i = 0; i < manyCars.Count(); i++)
Console.WriteLine(manyCars[i].ConvertToString());
Console.WriteLine(oneCar.ConvertToString());
}
static void Main(string[] args)
{
Program prg1 = new Program();
prg1.Init();
}
}
The output is this:
1993Nissan240SX
2001IsuzuRodeo
2010FordPinto
2010FordPinto
Why is the third line reading Pinto instead of F150? It seems to be setting the oneCar variable to be a pointer or something. How can this be avoided? I thought that’s what the "new" keyword accomplished.
Thanks in advance for any help.
Because
Carsis an object, and objects areReference Typesin C#.When you call this line of code:
You are pointing
oneCarto the memory location ofmanyCars[2]. They are referencing the same object. UpdatingoneCaralso updatesmanyCars[2].This link has a good writeup on Reference and Value types.