kosnkov kosnkov - 4 months ago 10
C# Question

List not changed outside the method

I noticed interesting action, when I change list inside some method, and throw exception inside this method, then out of scope of the method list is not changed.

How to change force this list to be changed in catch block? using out ?

List<string> list = null;
try
{
list = new List<string>{"1", "2", "3"};
ChangeMyList(list);
}
catch
{
//here list has 3 elements , why ?
}

void ChangeMyList(List<string> list)
{
list = list.Except(new List<string>{"1", "2"}).ToList();
//here this list has only one element
throw new Exception();
}

Lee Lee
Answer

Inside ChangeMyList, list is a copy of the reference to the source list pointed to by list in the outer scope. Assigning to this local reference does not affect the reference in the caller. You can use ref to pass list by reference:

void ChangeMyList(ref List<string> list)
{
    list = list.Except(new List<string>("1", "2")).ToList();
    //here this list has only one element
    throw new Exception();
}

then

List<string> list = new List<string>{"1", "2", "3"};
ChangeMyList(ref list);