From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

Don't mutate input arguments

Don't mutate input arguments

We have to remember, you don't want to mutate the input arguments; otherwise, you've got a side effect. Let me show you how that could happen. Remember this code from the previous example? I have the shared state here. This list of ints of the odd numbers, and then when I called AddNumbersToList(), I added these two numbers. So following this new principle of where we pass in the list, I can still run into issues. Here, I refactored my code. Now I have an AddNumbersToList() that takes a list of int as the input, and the total of the numbers now takes the list as input. This one is still pure because it's just for reaching over that input list passed in and returning the total. But look what's happening here. I'm passing in a list of int and I'm adding two items to it. So this is a side effect. So just like the last example, if I check the count of the list before I call AddNumbers, it's going to be lower than after I call AddNumbersToList(). So don't mutate the input state.

Contents