ICYMI C# 8 New Features: Prevent Bugs with Static Local Functions

This is part 6 in a series of articles.

C# 7 introduced local functions that allow you to create functions “local” to another function or method. These local functions are implicitly private to the enclosing function and cannot be accessed by other methods/properties/etc.  in the class. You can read more about local functions in this previous article.

C# 8 introduced the ability to make local functions static. This can help prevent bugs when using local functions.

Take the following code:

[Fact]
public void NestedCs7()
{
    int a = 10;

    int result1 = Add(10, 5);

    Assert.Equal(15, result1); // True, pass

    int result2 = Add(15, 2);

    Assert.Equal(17, result2); // False, fail

    int Add(int num1, int num2)
    {
        return a + num2;
    }
}

In the preceding code, the Add function is a local function. However there is a bug in this Add method, we are accidently referencing the variable a from the enclosing method NestedCs7. This means that instead of adding num1 and num2 and returning the result, we are adding a and num2. This will cause errors in the application.

Sometimes it may be convenient to reference (“capture”) the enclosing methods variables but to be more explicit and prevent unintended side-effects and bugs, from C# 8 you can make the method static.

In the following code we make the Add method static:

[Fact]
public void NestedCs8()
{
    int a = 10;

    int result1 = Add(10, 5);

    Assert.Equal(15, result1); 

    int result2 = Add(15, 2);

    Assert.Equal(17, result2); 

    static int Add(int num1, int num2)
    {
        return a + num2;
    }
}

If we try and build the preceding code, we’ll get a compilation error: Error CS8421    A static local function cannot contain a reference to 'a'.

This error tells us we’ve accidentally captured a and we can go and fix the bug:

[Fact]
public void NestedCs8()
{
    int a = 10;

    int result1 = Add(10, 5);

    Assert.Equal(15, result1); // True, pass

    int result2 = Add(15, 2);

    Assert.Equal(17, result2); // True, pass

    static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading