functional-workshop

functional programming principles applied in C#


Project maintained by B1tF8er Hosted on GitHub Pages — Theme by mattgraham

Side Effects

To clarify this definition, we must define exactly what a side effect is. A function is said to have side effects if it does any of the following,

using static System.Console;

internal class TestSideEffects
{
    internal static void Run()
    {
        var ab = JoinWithLogs("a", "b");
        var abab = JoinWithLogs(ab, ab);

        WriteLine(ab);
        WriteLine(abab);
    }

    private static string JoinWithLogs(string lhs, string rhs)
    {
        // Here we have the side effect of writing to console
        // but it could be any I/O operation.
        WriteLine($"lhs before: {lhs}");
        WriteLine($"rhs before: {rhs}");

        var result = $"{lhs}{rhs}";

        WriteLine($"result: {result}");
        return result;
    }
}