Home > Back-end >  How to keep the changes made to a parameter?
How to keep the changes made to a parameter?

Time:05-25

I have a function that, under certain conditions, adds an object to a list.

void Func(out List<Move> moves, Move move)
{
    if (conditions) moves.Add(move);
    
    return;
}

I thought that an out parameter could be changed within the function and keep the changes outside of it, but this code gives me a exception saying the out parameter must always be assigned. The whole purpose of the function is to filter out certain items preventing them from being put in the list.

It's my first time using an out parameter, so I might have misunderstood how it works.

Any help would be appreciated!

CodePudding user response:

I don't think you need an "out" parameter in this case. List<> is a reference type, so adding/removing to it in the function should keep the changes outside of it as well.

The "out" keywords means you want to pass the argument by reference instead of by value. Non-reference types like int, decimal, bool, structs and so on are passed by value meaning that usually, changes made to them inside a function are discarded once outside the function scope.

However, reference types like Objects, Lists and so on are always passed by reference so there is no need for the "out" parameter with them. Changes made to them will always be preserved even when you leave the scope of the function. Assuming, of course, you make changes to the objects they are pointing at, if you assign a new object I don't think that will persist

  • Related