'C# Object Array Changing all element properties [closed]
Just started learning C# and struggling to understand what is happening. Here is a simplified version of my problem.
I have two classes called Dog and Kennel. Kennel houses a 2D array of type Dog. Dog has multiple properties (breed, color), but just _name is all we need for this example.
I want to change the name of a single dog. I tried:
kennel.Dogs[4,4].Name = "Fido"
but it sets ALL the dogs to the name of "Fido". Not just the dog at (4, 4). Why?
Example:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
Kennel kennel = new Kennel();
kennel.Dogs[4,4].Name = "Fido";
Console.WriteLine(kennel.Dogs[4,4].Name); //Expectation: Fido; Result: Fido
Console.WriteLine(kennel.Dogs[2,2].Name); //Expectation: Bowser; Result: Fido
}
}
class Kennel {
public Kennel() {
this._dogs = new Dog[10,10];
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++) {
_dogs[i, j] = defaultDog;
defaultDog.Name = "Bowser";
}
}
}
private string _name;
private Dog defaultDog = new Dog();
private Dog[,] _dogs;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Dog[,] Dogs
{
get { return _dogs; }
set { _dogs = value; }
}
}
class Dog {
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
