Create different objects of model

  • A+
Category:Languages

I have a simple model like this:

public class AssignStatisticsModel {     public string TasksName { get; set; }     public int Time { get; set; } } 

I want to create four objects into it like:

List<AssignStatisticsModel> textModels = new List<AssignStatisticsModel>(); AssignStatisticsModel textmodel = new AssignStatisticsModel();  textmodel.TasksName = "Progress to Back Check"; textModels.Add(textmodel); textmodel.TasksName = "Back Check to Corrections"; textModels.Add(textmodel); textmodel.TasksName = "Corrections to Completed"; textModels.Add(textmodel); textmodel.TasksName = "Progress to Completed"; textModels.Add(textmodel); 

But for some reason all TasksNames called "Progress to Completed" instead create one with each TasksName I added. Why last textModels.Add(textmodel); replace four objects with same TasksName?

 


You have to create a new textmodel object each time. What you've done is added the same object 4 times to the list:

List<AssignStatisticsModel> textModels = new List<AssignStatisticsModel>();  var textmodel = new AssignStatisticsModel { TasksName = "Progress to Back Check" }; textModels.Add(textmodel); textmodel = new AssignStatisticsModel { TasksName = "Back Check to Corrections" }; textModels.Add(textmodel); textmodel = new AssignStatisticsModel { TasksName = "Corrections to Completed" }; textModels.Add(textmodel); textmodel = new AssignStatisticsModel { TasksName = "Progress to Completed" }; textModels.Add(textmodel); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: