Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: C#


How to Enjoyably Develop .NET with AnduinOS

This article aims to provide .NET developers with a guide for setting up a development environment in VSCode on AnduinOS or any Linux system that closely mimics the Visual Studio experience. It begins by noting that, due to the lack of a free Visual Studio and the absence of a Rider Community Edition, VSCode emerges as an ideal alternative. The core content recommends the C# extension and its key settings, such as enabling OmniSharp decompilation support, EditorConfig, and the Roslyn analyzer, to enhance basic functionality. For advanced needs, it introduces the C# Dev Kit and its intelligent completion components, while cautioning about its commercial licensing restrictions and account login requirements. Additionally, it recommends Roslynator as a lightweight alternative for code analysis and refactoring, along with practical plugins for automatically generating XML documentation comments and completing namespaces. The article also briefly discusses the pros and cons of GitHub Copilot. The author emphasizes that these configurations can significantly improve development efficiency and invites readers to share further optimization suggestions, aiming to help developers achieve a smoother C# development experience on Linux platforms.

Views 312
.NET AnduinOS C# VSCode development-environment dotnet github-copilot vscode-plugins

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

What is the difference between Linq and lambda?

This article aims to clarify the concepts of LINQ and Lambda expressions, which are often confused, by pointing out that the two are fundamentally different. LINQ, or Language Integrated Query, is essentially a collection of extension methods; it can be used with either query expression syntax or method syntax. Lambda expressions, on the other hand, are a form of syntactic sugar designed to simplify the creation of anonymous delegates, where the arrow symbol represents the return operation. In method syntax, Lambda expressions are commonly used as parameters to construct `Func` delegates, but developers can also use named methods as an alternative, with both approaches being functionally equivalent. An advanced use of Lambda expressions is their ability to build expression trees, representing code as data. This enables LINQ to convert C# query statements into other forms, such as SQL, which is also the underlying principle behind many ORM frameworks. The article emphasizes that although the two concepts often appear together in documentation, developers should master the fundamental principles and avoid blindly chasing new technologies at the expense of core knowledge. By distinguishing between the methods of creating delegates and the nature of query libraries, developers can clearly understand the differences between the two.

Views 173
C# Method Syntax entity relationship mapping expression trees lambda expressions linq

C# required: Say goodbye to null reference exceptions with strings

The article discusses the issue of null reference exceptions for strings in C# and presents solutions. The author points out that although Tony Hoare famously referred to the introduction of null as a "billion-dollar mistake," in practical development, `string` is often misused as a value type despite being a reference type. This misuse leads to the default `null` value triggering `NullReferenceException`. Prior to C# 11, developers typically used `null!` to force non-null status or declared variables as `string?` to suppress warnings. However, this approach often masks the underlying inconsistency between database fields that can be null and code logic that expects non-null values, making it highly susceptible to causing production incidents in teams lacking rigorous testing. The `required` keyword introduced in C# 11 offers a superior solution by mandating that non-null strings be assigned during object initialization, thereby eliminating null reference risks at compile time. Finally, using this technical topic as a springboard, the article criticizes certain teams that adopt an "outsourcing model" of compressing working hours to pursue performance metrics. The author argues that this practice sacrifices software quality; not only does it fail to genuinely accelerate product iteration, but it also leads to user churn due to code defects, ultimately undermining the long-term competitiveness of their own products.

Views 195
C# Code Quality Engineering Practices Nullables Software Product Management required keyword

What is the principle behind asynchrony? How does C# implement asynchrony based on state machines?

This article provides an in-depth analysis of the state machine implementation principles behind the `await` keyword in C# asynchronous programming. The compiler converts `async` methods into nested struct state machines, initializing and starting the state machine through stub methods. The core lies in the `MoveNext` method, which is responsible for executing specific logic and managing state transitions. When encountering `await`, if the asynchronous operation has already completed, it takes the fast path and continues directly; if it is not yet complete, it takes the slow path, saving the current state and `awaiter` information before pausing execution, and resuming from the breakpoint once the operation completes. The article details the mechanisms where the state code `state` is used to locate the resumption point, the `awaiter` field is used to retrieve the result, and the `builder` is used to handle exceptions and return the final result. Through this design, C# achieves a non-blocking asynchronous execution model, ensuring code readability while avoiding the performance overhead associated with thread blocking, thereby thoroughly revealing how `await` expressions coordinate asynchronous operations at the low level through state switching and continuation mechanisms.

Views 285
Async Execution C# C# async programming Exception Handling Execution Paths State Machine

What is asynchrony? Is asynchrony the same as multithreading? Is asynchrony just `async` and `await`?

This article provides an in-depth analysis of the fundamental differences between `await` and `Task` in C# asynchronous programming. Through code-based evidence, it demonstrates that it is `Task.Run`, not the `await` keyword, that initiates a new thread. The core function of `await` lies in non-blockingly waiting for asynchronous operations to complete, creating continuations, and unwrapping `Task<T>` to retrieve return values. The article corrects the common misconception that one must use `await` to invoke asynchronous methods, clarifying that calling an asynchronous method starts its execution immediately. Developers can execute other logic before `await`, thereby enabling the parallel execution of multiple asynchronous tasks to optimize performance. Additionally, the article introduces methods for returning already-completed tasks using `Task.FromResult` and `Task.CompletedTask` without using the `async` modifier, and recommends using `Task.WhenAll` to wait simultaneously for multiple independent tasks to complete. Finally, it emphasizes the importance of understanding underlying principles for the safe and efficient use of asynchronous programming.

Views 119
Async Await C# Multithreading Task Task Parallelism dotnet

When and Why to Use the `IsUnicode` Method in EF Core

This article provides an in-depth analysis of the practical impact of the `IsUnicode()` configuration in Entity Framework Core on MariaDB and MS SQL Server. Experiments show that this configuration has no effect on MariaDB because the default character set `utf8mb4` already supports Unicode; however, in MS SQL Server, it determines whether string fields are mapped to `nvarchar` or `varchar`. Using `nvarchar` ensures correct storage of Chinese characters and emojis, whereas `varchar` results in garbled non-ASCII characters. The article recommends using `IsUnicode(false)` only when it is confirmed that field content is ASCII-safe (such as pure numbers or English text) to save storage space and improve memory efficiency, particularly when handling massive amounts of data. For URLs or user-generated content, it is advisable to maintain the default Unicode support, even if the content appears safe, to prevent data anomalies caused by special characters or internationalized content entered by users. Additionally, EF Core 6 introduced the `Unicode` attribute as an alternative configuration method. In conclusion, when the data content is uncertain, default Unicode support should be prioritized to ensure system robustness and data integrity, thereby avoiding potential business risks associated with excessive optimization of storage space.

Views 146
C# Database Design EF Core Entity Framework Core IsUnicode Method Model Configuration

Simplifying DDD Value Object Comparison with EF Core Dynamic Expression Trees

This article explores technical solutions for implementing semantic equality queries with value objects in EF Core. It first points out that traditional field-by-field query code is verbose and lacks semantic clarity, while directly comparing value objects for equality results in a compilation exception. To address this, the article proposes and implements a generic `ValueObjectEqualHelper` static class, whose core is the `CheckEqual` method. This method dynamically builds expression trees, iterates through the value object's properties, automatically skips null values to avoid generating redundant `IS NULL` conditions, and correctly constructs binary expression trees for equality comparisons based on property types (primitive or reference types), finally connecting all conditions with `AndAlso` logic. This approach preserves the intuitive semantics of `p => p.Address == new Address(...)` while being correctly translated into SQL by EF Core, solving the pain point of being unable to directly compare value objects for equality in database queries and providing a generic and elegant implementation path.

Views 168
.NET C# Dynamic Condition Generation EF Core Entity Framework Core expression trees

Building C# Expression Trees Step by Step

This article uses the construction of the common Lambda expression `p => p.Age > 18` as an example to demonstrate in detail the entire process of manually building an expression tree in C#. The article first analyzes the correspondence between the elements of the expression and the tree nodes, then step-by-step shows how to sequentially create parameter expressions, member expressions, constant expressions, and binary operator expressions. Finally, it uses `Expression.Lambda` to combine these nodes into a complete Lambda expression. The text also includes actual code for compiling the expression and using it for list filtering. Addressing the question of why manual compilation might seem redundant, the article points out that its core value lies in its use with `IQueryable` and EF Core, enabling dynamic queries without the need for manual compilation. This technique can be used to simplify dynamic comparison of value objects in DDD, or to set global filters for entity properties (such as soft delete), thereby enhancing code flexibility and maintainability.

Views 121
.NET C# Dynamic Expression EF Core Linq Expressions expression trees

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