Code Trivia #1

What do you think this code will print?

public static void Main()
{
    var countries = new List<string>() { "PT", "GB", "ES", "FR" };

    var filter = GetEuroCurrencyCountriesFilter();

    var euroCurrencyCountries = countries.Where(filter).ToArray();

    Console.WriteLine(String.Join(", ", euroCurrencyCountries));
}

private static Func GetEuroCurrencyCountriesFilter()
{
    Func<string, bool> filter = c => false;

    var euroCurrencyCountries = new string[] { "PT", "FR", "ES" };

    foreach (string countryCode in euroCurrencyCountries)
    {
        var previousFilter = filter;

        filter = c => (previousFilter(c) || c == countryCode);
    }

    return filter;
}

Your first guess may surprise you.


Update:

The code above ends up printing only “ES” because the used filter function (closure) obtained from the helper method still has access to the context where it was created and where the countryCode variable used in each short-circuited comparison will hold the last value iterated since it’s declared at the same scope that the filter function.

A workaround is to declare a new variable in each iteration and create the comparison referring to that new variable. This way the result will be: “PT, ES, FR”.

private static Func GetEuroCurrencyCountriesFilter()
{
    Func<string, bool> filter = c => false;

    var euroCurrencyCountries = new string[] { "PT", "FR", "ES" };

    foreach (string countryCode in euroCurrencyCountries)
    {
        string newCoutryCodeVariable = countryCode;

        var previousFilter = filter;

        filter = c => (previousFilter(c) || c == newCoutryCodeVariable);
    }

    return filter;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s