Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading