Reputation: 8646
I have class in C# -
public class Availability
{
public ushort RegionId {get;set;}
}
Then , I have a method GetListOfClassesAsPerIterations(Availability xiAvailability)
I have List in this method where I want to append different values of RegionId.
Eg. First 100 elements in List with RegionId=1500 , next 100 elements with RegionId=1400
But what is happening is , when I add first 100 elements in list with RegionId=1500 , and then try to add next 100 elements in list with RegionId=1400 , all the items in List becomes with RegionId=1400.
I have written code for it as -
var lstAvailability = List<Availability>
for (int i = 0; i < 100; i++)
{
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
for (int i = 0; i < 100; i++)
{
xiAvailability.RegionId = 1400;
lstAvailability.Add(xiAvailability);
}
Here I can see all the 200 elements with RegionId as 1400. But instead , I was expecting first 100 to be with 1500 and next 100 to be with 1400.
What could be the alternative?
Upvotes: 0
Views: 182
Reputation: 21
Object in the list is a reference to the actual object. Hence, you're seeing the latest value of 1400 for RegionId.
You can try the below,
var xiAvailability1500 = new Availability();
xiAvailability1500.RegionId = 1500;
var xiAvailability1400 = new Availability();
xiAvailability1400.RegionId = 1400;
var lstAvailability = List<Availability>();
for (int i = 0; i < 200; i++)
{
if (i < 100)
lstAvailability.Add(xiAvailability1500);
else
lstAvailability.Add(xiAvailability1400);
}
Upvotes: 2
Reputation: 123
Here is another alternative way:
var lstAvailability = List<Availability>
int count = 0;
for (int i = 0; i < 200; i++)
{
if(count => 0 && count <= 100)
{
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
if (count => 100)
{
xiAvailability.RegionId = 1400;
lstAvailability.Add(xiAvailability);
}
count = count + 1;
}
Upvotes: 1
Reputation: 36
This is because you are putting 200 references to the same object in the list. If you want to have 200 different objects, then you need to do something like this:
var lstAvailability = new List<Availability>();
for (int i = 0; i < 200; i++)
{
var xiAvailability = new Availability();
if (i < 100)
xiAvailability.RegionId = 1400;
else
xiAvailability.RegionId = 1500;
lstAvailability.Add(xiAvailability);
}
If you need to have 100 references to 2 objects, then do this
var lstAvailability = new List<Availability>();
var xiAvailability = new Availability() { RegionId=1400 };
for (int i = 0; i < 200; i++)
{
if (i == 100)
xiAvailability = new Availability() { RegionId = 1500 };
lstAvailability.Add(xiAvailability);
}
Upvotes: 2