Implementing Inline Functions in C#: Methods and Best Practices

Nov 24, 2025 · Programming · 9 views · 7.8

Keywords: C# | Inline Functions | Lambda Expressions | Anonymous Methods | Local Functions | Delegates

Abstract: This article provides an in-depth exploration of various methods to implement inline functions in C#, including anonymous methods, lambda expressions, and local functions. Through detailed code examples and comparative analysis, it explains the characteristics, applicable scenarios, and performance considerations of each syntax across different C# versions. Special attention is given to practical applications in contexts like LINQ to XML for data transformation and computation, offering comprehensive technical guidance for developers.

Concept and Value of Inline Functions

In C# programming, inline functions allow developers to define and use function logic directly where needed, without declaring separate methods at the class level. This approach is particularly useful for logic that is only relevant in specific contexts, such as data transformation, conditional calculations, or event handling. By using inline functions, code becomes more compact and readable, while reducing unnecessary class member clutter.

Anonymous Methods (C# 2.0)

Anonymous methods, introduced in C# 2.0, implement inline functions using the delegate keyword. They are suitable for scenarios requiring multiple statements or complex logic. For example, defining an addition function:

Func<int, int, int> add = delegate(int x, int y)
{
    return x + y;
};

If the function ignores parameters, the parameter list can be omitted:

Action helloWorld = delegate
{
    Console.WriteLine("Hello world!");
};

In LINQ to XML, anonymous methods can process prefix strings, such as removing spaces:

Func<string, string> processPrefix = delegate(string prefix)
{
    return prefix?.Replace(" ", "") ?? "";
};
new XElement("Prefix", processPrefix(Prefix));

Lambda Expressions (C# 3.0)

Lambda expressions offer a more concise syntax, available in two forms: expression lambdas and statement lambdas.

Expression Lambdas

Expression lambdas are ideal for single-line return values, with compiler-inferred parameter types:

Func<int, int, int> add = (x, y) => x + y;

Statement Lambdas

Statement lambdas allow multiple statements, defined with curly braces:

Func<string, string> processPrefix = (prefix) =>
{
    if (string.IsNullOrEmpty(prefix)) return "";
    return prefix.Trim().ToUpper();
};

In XML element creation, use lambdas directly for data processing:

new XElement("Prefix", (Prefix == null ? "" : Prefix).Where(c => char.IsLetterOrDigit(c)).ToArray());

Local Functions (C# 7.0)

Local functions are defined within a method, with syntax similar to regular methods but scoped to the containing method:

void ProcessXml()
{
    string ProcessPrefix(string source)
    {
        return source?.Replace(" ", "").ToLower() ?? "";
    }
    
    new XElement("Prefix", ProcessPrefix(Prefix));
}

Local functions support recursion and more complex logic, often with better performance than delegates.

Delegate Types: Func and Action

Inline functions are typically assigned to delegate types. Func is used for methods with return values, where the last type parameter specifies the return type; Action is for methods without return values. For example:

Func<string, string, int> compare1 = (l, r) => l.CompareTo(r);
Action<string> print = s => Console.WriteLine(s);

Other delegate types like Comparison<T> can use similar syntax:

Comparison<string> compare2 = (l, r) => l.Length.CompareTo(r.Length);

Practical Applications and Invocation

Inline functions can be invoked like regular methods:

int result = add(5, 3); // returns 8
print("Processed"); // outputs "Processed"

In LINQ to XML, combine inline functions for dynamic data processing:

var element = new XElement("Data", 
    new XElement("Prefix", Prefix == null ? "" : string.Concat(Prefix.Where(c => !char.IsWhiteSpace(c)))));

Version Compatibility and Selection Advice

When choosing an inline function method, consider the C# version:

In real-world projects, evaluate logic complexity, readability requirements, and team standards to select the most appropriate implementation.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.