Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: Functional Programming


How to Use the Optional Pattern to Solve Nuisance Null Reference Issues in C#

This article provides an in-depth comparison of the application differences between the Optional pattern and the Nullable feature in C#. Through concrete code examples using `Person` and `Book` classes, it demonstrates the frequent null checks, nullable operators, and conditional statements required when using Nullable, whereas the Optional pattern achieves more elegant chained calls through functional operations such as `Map` and `Reduce`. Although the Optional pattern may appear slightly more complex initially, it fundamentally eliminates the propagation of null values, thereby avoiding runtime null reference exceptions and exposing potential errors earlier at the compilation stage. The article notes that the Optional pattern is particularly suitable for scenarios with high safety requirements or where avoiding common null pitfalls is desired, while Nullable is more intuitive and readable. Finally, it recommends that developers flexibly choose the most suitable null-handling approach based on project scale, team technical background, and specific needs, as both are effective means of solving null reference issues.

Views 315
C# Functional Programming Null Handling Null Safety Optional Pattern Type System

How to use C# expression trees?

Expression trees are a technique that uses tree-based data structures to represent the logic of code operations. In .NET, they correspond to the `Expression<TDelegate>` type. They allow code to be manipulated as data, and can be compiled into executable delegate objects via the `Compile` method. This article demonstrates, through a hands-on example of manually constructing an expression tree, how to replace hardcoded property name validation logic. The specific steps include: first, creating a `ParameterExpression` as the parameter node; next, using `Expression.PropertyOrField` or `MakeMemberAccess` to build member access nodes; and finally, assembling a complete Lambda expression via `Expression.Lambda` and invoking it using `DynamicInvoke`. This approach effectively resolves maintenance challenges caused by property name changes, enhancing code flexibility and maintainability. Although dynamically constructing expression trees involves relatively complex and less intuitive code, its advantages are significant in scenarios requiring the avoidance of hardcoding and the implementation of runtime dynamic logic. It serves as an effective means of simplifying complex query operations, such as comparing value objects.

Views 106
C# Dynamic Code Generation Functional Programming Property Access expression trees lambda expressions