Laura
Laura

Reputation: 161

Unwanted member change because of reference

I am writing a piece of code but cannot figure out why it is showing some (from my point of view) weird behaviour. I get this is due to how I have written the code, but I cannot understand why it is not doing what I want it to do.

I have an eventhandler:

private void heatFinishedHandler(object sender, List<Kart> e)
    {
        mainForm.enableControls();
        server.karts = e;
    }

If I add e.Clear(); to it, it also clears server.karts.

The argument e comes from another class:

private List<Kart> kartlist = new List<Kart>();

heatFinished?.Invoke(this, kartlist);

The heatFinished event and the heatFinishedEventHandler are connected.

What do I need to do to get e by value, instead of reference? Or is it a value type, but is it pointing to kartlist?

I want to be able to get the value of e and store it in server.karts, not being able to change kartlist.

Upvotes: 0

Views: 36

Answers (1)

asgerhallas
asgerhallas

Reputation: 17724

Make a copy of the list you pass to the function like

private List<Kart> kartlist = new List<Kart>();

heatFinished?.Invoke(this, kartlist.ToList());

Or do it inside the function like

private void heatFinishedHandler(object sender, List<Kart> e)
{
    mainForm.enableControls();
    server.karts = e.ToList();
}

.ToList() will make a new List-instance with the same values as the original one.

Upvotes: 4

Related Questions