0
I have a list of objects that I am filling it in as follows:
var props = type.GetRuntimeProperties();
var obj = new T();
for (int i = 0; i < readerCache.Count; i++)
{
var prop = props.Single(x => x.GetColumnName().ToLower() == readerCache.ElementAt(i).Item1.ToLower());
if (prop.GetCustomAttribute<Column>().Type == ColumnType.FK)
{
var method = typeof(SelectExtension).GetMethod("SelectSingle");
var generic = method.MakeGenericMethod(prop.PropertyType);
prop.SetValue(obj, generic.Invoke(null, new object[] { dBManager, $"WHERE id = '{readerCache.ElementAt(i).Item2}'" }));
}
else
{
prop.SetValue(obj, readerCache.ElementAt(i).Item2);
}
if ((i + 1) % props.Count() == 0)
{
objList.Add(obj);
}
}
When I am debugging, the objects are being filled in correctly, but when the list finishes being filled in, all the elements are equal.
My suspicion is that it is passing the object by reference, and not by value.
Why does this happen? How to fix?
You shouldn’t be declaring
obj
inside the loop?– bfavaretto
You couldn’t, because obj is only complete after you’ve been through the loop a few times. Doing it the way you said it would instantiate it all the time.
– Francisco
Do you have any field that differs between all objects? If yes just do a check
– PauloHDSousa