Moonglade

Modern Markdown blogging with AI-powered localization and search.

All Posts


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

A comic strip explaining the principles of .NET garbage collection (GC)

Set against the backdrop of the 2023 Lunar New Year's Eve, this article explores the prevalent "assembly-line" development predicament faced by .NET developers in China. It points out that many developers focus solely on business-level CRUD operations while neglecting underlying technical principles, which hinders their long-term career growth. The author advocates breaking through this bottleneck via performance optimization, emphasizing that reducing Garbage Collection (GC) pressure is the core entry point for .NET performance tuning. The article translates and introduces a classic .NET GC principle comic created by Redgate, aiming to provide foundational technical education for developers. Additionally, it offers an in-depth analysis of the technical challenges involved in Large Object Heap (LOH) compaction. It mentions a temporary workaround involving setting `GCSettings.LargeObjectHeapCompactionMode` to `CompactOnce`, but notes that this method has time-sensitivity limitations and requires manual intervention, effectively reverting to the complexity of manual memory management. The article advises readers to deepen their understanding of .NET's memory management mechanisms by adopting a multi-language programming perspective.

Views 187
.NET comic translation dotnet garbage collection large object heap performance optimization

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

How is .NET compiled? How do you read the intermediate language?

This article provides an in-depth analysis of the compilation mechanism of C# on the dotnet platform, highlighting its hybrid approach that combines static compilation with Just-In-Time (JIT) compilation. First, the compiler statically compiles C# source code into Common Intermediate Language (CIL/IL) and encapsulates it in PE or PE+ executable files. This stage involves NuGet package restoration and building in either Debug or Release mode; the Release mode offers better performance and security due to the removal of debugging information. Subsequently, at runtime, the Common Language Runtime (CLR) takes over the process, using the JIT compiler to dynamically convert IL into native machine code specific to the current platform, thereby achieving a balance between cross-platform compatibility and execution efficiency. The article also uses the Pythagorean theorem as an example to detail the structure of the IL instruction set, including method declarations, stack operations, local variable initialization, and specific execution logic, helping readers understand the actual low-level mapping of the code. Mastering this process not only helps eliminate doubts about the compilation black box but also enables more precise judgments when optimizing performance or comparing the overhead of different implementations by reading IL code.

Views 188
.NET .NET Framework C# Compilation Intermediate Language JIT Compiler performance optimization

[Translation] .NET SDK Will Have Built-in Container Support, No Longer Requiring a Dockerfile

This article introduces the new container image build feature in the .NET 7 SDK, designed to resolve the issue of missing configuration files caused by inconsistencies between the traditional Dockerfile build context and the dotnet build process. By leveraging the new TAR API introduced in .NET 7, this feature generates container images directly via MSBuild properties, eliminating the need to write complex Dockerfiles. Its core advantage lies in seamless integration with existing build logic. It automatically selects a Debian-based base image by default and supports customizing the image name, version, and underlying system (such as Alpine) through properties like ContainerBaseImage. Although it currently does not support executing RUN commands, pushing to remote repositories, or creating Windows images, custom base images can be used to meet native dependency installation needs, and these features will be progressively enhanced in future versions. The article recommends trying this feature in local development or CI pipelines to simplify the containerization workflow. While Dockerfiles remain more flexible, the SDK-integrated approach offers a more convenient automated experience in specific scenarios.

Views 172
.NET .NET SDK Container Builds Docker GitHub Actions Linux x64

Still memorizing the concept of dependency injection? Why not write your own dependency injection framework?

This article introduces the core implementation and testing process of KDI, a custom Dependency Injection (DI) framework built with C#. KServiceProvider registers services by iterating through KServiceCollection. For the Transient lifetime, it uses Func delegates to ensure a new instance is created every time a service is requested. For the Singleton lifetime, it leverages Lazy objects to implement lazy loading while guaranteeing global uniqueness. Through Guid service tests, the correctness of both lifetimes was verified: Singleton returns the same instance on multiple requests, whereas Transient returns a different instance each time. The article concludes with a profound critique of exam-oriented programming learning mindsets, pointing out that Scoped and Singleton behaviors have fundamental differences in console applications. Blindly applying interview techniques can lead to misunderstandings of underlying principles. The author emphasizes the importance of deeply understanding Dependency Injection mechanisms rather than rote memorization, and reminds readers to be aware of the security risks associated with the Service Locator pattern in production environments, as well as the room for improvement in the framework. Developers are encouraged to abandon rigid thinking and cultivate genuine creativity.

Views 130
.NET Dependency Injection DependencyInjection Design Patterns Service Lifecycles Software Engineering

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