I cant understand why the below is happening.
See the code and output example.
Why are the 3 array elements outputting the same value when they are clearly being set to different values.
Jim
Frank
James
James
James
James
class Program
{
static void Main(string[] args)
{
users allUsers = new users();
allUsers.user = new usersUser[3];
usersUser userConfig = new usersUser();
userConfig.username = "Jim";
allUsers.user[0] = userConfig;
Console.WriteLine(allUsers.user[0].username);
userConfig.username = "Frank";
allUsers.user[1] = userConfig;
Console.WriteLine(allUsers.user[1].username);
userConfig.username = "James";
allUsers.user[2] = userConfig;
Console.WriteLine(allUsers.user[2].username);
Console.WriteLine("");
Console.WriteLine(allUsers.user[0].username);
Console.WriteLine(allUsers.user[1].username);
Console.WriteLine(allUsers.user[2].username);
Console.ReadLine();
}
}
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class users {
private usersUser[] userField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("user")]
public usersUser[] user {
get {
return this.userField;
}
set {
this.userField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.1432")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class usersUser {
private string usernameField;
/// <remarks/>
public string username {
get {
return this.usernameField;
}
set {
this.usernameField = value;
}
}
}
Because you are changing the same object over and over before assigning it, hence you are changing it even for the ones that are already assigned, the last name you set it to is the one that sticks. You have to do it like:
Create new objects for each index in the array, instead of using the same three times.