adding a new value to list overwrite previous values in the list

Advertisements

I’m trying to add multiple items to a list but at the end all items have the same value equal to last item

public static List<Ausencias> SeparateMonth(Ausencias aus)
{
    List<Ausencias> ausencias = new List<Ausencias>();
    try
    {
        var resultSplit = Helper.SplitFechas(aus.PI_StartDate, aus.PI_EndDate);

        if (resultSplit.Count > Constant.ONE)
        {                 
            foreach (var item in resultSplit)
            {
                Ausencias ausenc = new Ausencias();
                ausenc = aus;
                
                ausenc.PI_StartDate = item.StartDate;
                ausenc.PI_EndDate = item.EndDate;

                ausencias.Add(ausenc);
            }
        }
    }
    catch (Exception ex)
    {
        ex.Data.Clear();
    }
    return ausencias;
}

Previously I was the asenci var outside for, but moving the var also don’t work

>Solution :

ausenc = aus; replaces the newly created ausenc instead of assigning it its properties. Note that classes are reference types. Therefore, variables of these types contain a reference (or address) to an object, not the object with its fields, and the assignment only copies the reference but does not make a copy of the object or copy its contents to another object. Currently you end up in having a list with references to the same aus object.

If you want to assign the properties of another object of the same type, create a so called copy constructor:

public class Ausencias
{
    public Ausencias() {}

    public Ausencias(Ausencias other)
    {
        Prop1 = other.Prop1;
        Prop2 = other.Prop2;
        Prop3 = other.Prop3;
    }

    // ... properties here
}

Then in your loop

Ausencias ausenc = new Ausencias(aus);

ausenc.PI_StartDate = item.StartDate;
ausenc.PI_EndDate = item.EndDate;

ausencias.Add(ausenc);

Leave a Reply Cancel reply