Blog

Filter posts by Category Or Tag of the Blog section!

Local function in C#

Saturday, 09 February 2019

Local functions in C# are functions that are defined inside another function, method, or property. They are a feature introduced in C# 7.0 and provide a way to encapsulate and organize code within a containing method, making it more readable and maintainable. Local functions have access to the variables and parameters of their containing method, which can be useful for simplifying complex logic. Here's the basic syntax for defining a local function:

 


returnType ContainingMethod()

{

    // Other code here



    returnType LocalFunction(parameterList)

    {

        // Local function code here

    }



    // Other code here



    // You can call the local function within the containing method.

    var result = LocalFunction(argumentList);



    // Other code here

}

 

Here's an example of how you might use a local function:


 

public int CalculateSum(int a, int b)

{

    int Add(int x, int y)

    {

        return x + y;

    }



    int result = Add(a, b);



    return result;

}

 

In this example:

  • Add() is a local function defined inside the CalculateSum method.
  • It takes two parameters x and y.
  • It calculates their sum and returns the result.

 

Local functions can be useful in scenarios where you need to perform a specific operation multiple times within a method, and you want to encapsulate that logic to improve code readability and maintainability.

 

Some key points to keep in mind about local functions:

  • They are only accessible within the containing method or property.
  • They can access variables and parameters from the containing method.
  • They are typically used for code that is not meant to be reused outside of the containing method.
  • They can be a good alternative to using nested classes or delegates for encapsulating logic.

 

Local functions are a powerful feature in C# that can help you write cleaner and more organized code, especially in situations where you have complex logic within a method. Where are the usages? Local functions in C# are used in scenarios where you want to encapsulate a piece of logic within a method, improving code organization and readability. Here are some common use cases for local functions:

 

  • Complex Calculations: Local functions can be used to encapsulate complex calculations or algorithms within a method. This can make the code easier to understand by breaking down the logic into smaller, named pieces:
     

public int CalculateTotal(int a, int b, int c)

{

    int Add(int x, int y) => x + y;

    int Multiply(int x, int y) => x * y;



    int sum = Add(a, b);

    int result = Multiply(sum, c);



    return result;

}

 

  • Validation: Local functions can be used for input validation within a method. This can help improve the readability of the validation code and reduce duplication.


 

public bool IsValidEmail(string email)

{

    bool IsNotEmpty(string str) => !string.IsNullOrWhiteSpace(str);

    bool ContainsAtSymbol(string str) => str.Contains("@");



    return IsNotEmpty(email) && ContainsAtSymbol(email);

}

 

  • Iterative Operations: Local functions can be used in iterative operations, such as loops, to encapsulate repetitive logic.


 

public void ProcessItems(IEnumerable<int> items)

{

    void ProcessItem(int item)

    {

        // Processing logic here

    }



    foreach (var item in items)

    {

        ProcessItem(item);

    }

}

 

  • Error Handling: Local functions can be used for error handling or custom exception generation within a method.

 

public void DoSomething()

{

    void LogError(string message)

    {

        // Log error message

    }



    try

    {

        // Some operation that might throw an exception

    }

    catch (Exception ex)

    {

        LogError(ex.Message);

        throw;

    }

}
 

 

  • Helper Functions: Local functions can serve as helper functions to break down a method into smaller, more focused pieces of logic.


 

public void ProcessData(IEnumerable<int> data)

{

    void Validate(int value)

    {

        // Validation logic

    }



    void Transform(int value)

    {

        // Transformation logic

    }



    foreach (var item in data)

    {

        Validate(item);

        Transform(item);

    }

}

 

Local functions are particularly useful when a piece of logic is used only within a specific method and doesn't need to be exposed outside of that method. They help make the code more modular and easier to maintain by isolating logic within the scope of the method where it's needed.

 

Category: Software

Tags: C#

comments powered by Disqus