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();
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With