C# extension methods to save the day

Introduction

Extensions methods, that are heavily used in LINQ and in fluent like interfaces, allow developers not just extend existing types but organize the code better. Especially functionalities related to those types. Also, extension methods can be used to add functionality to types we have no control upon them.

Case 1: Enumerations

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. Enums inherit from the Enum abstract class, but they are not treated as classes, thus they can’t have properties and methods. Let’s see an example where an Enum is needed to carry some logic.

Let’s analyze the following example:

And the output result is the following:

Case 2: Extending a Record type functionality

C# 9.0 introduces record types, which are a reference type that provides synthesized methods to provide value semantics for equality. Records are immutable by default.

Record types make it easy to create immutable reference types in .NET. There are many advantages to immutable reference types. These advantages are more pronounced in concurrent programs with shared data. Unfortunately, C# forced you to write quite a bit of extra code to create immutable reference types.

Records provide a type declaration for an immutable reference type that uses value semantics for equality. The synthesized methods for equality and hash codes consider two records equal if their properties are all equal.

So let’s say we want extend a Record type’s functionality. We want to keep the Record type clean, without any methods, just with properties that carry the data.

And the output result is the following:

You can organize your code by implementing initially a set of base record types with their extensions, and the child records carry the extensions methods of the parents classes they inherit from.

Case 3: Extending interfaces

Extending an interface might a controversial topic. For sure an interface must be as small as possible. If extending it, is right or wrong, I believe it depends on the requirements and the structure the code you want to have. I, personally, am open to it.

Let’s say have the following interface, and its extension methods. The Save method is not called directly, but it is called inside the extension methods. This could be a design issue.

Conclusions

Extensions methods are giving a more Functional Programming (FP) flavor to C#, and we will discuss about them more in the future. Extensions methods allows us to organize and group functionality outside of the classes, and this gives us the benefit of cleaner and more well organized code. Plus with the strategy design pattern we can choose which extension methods can be called in the runtime.