📎 Webclip
Using Extension Methods in C# to Build Fluent Code
The article explains that extension methods are static methods the compiler lets you call as if they were instance methods. It uses a book-building example to show how this syntax can make APIs more fluent while still relying on static classes and explicit return values.
Reading notes#
- Static methods belong to the class, not to a specific instance, and can only use instance data when it is passed in as a parameter.
- Extension methods are declared in static classes and mark the first parameter with
thisso the compiler allows instance-style calls. - The same extension method can be called as a static method or with extension syntax, and the compiler rewrites the latter into a static call.
- The article presents a
BookBuilderexample whereWrittenByis added as an extension method because the class itself is assumed to be unmodifiable. - Returning the builder instance from each extension method supports chaining and makes a fluent API possible.
- LINQ depends on extension methods, especially methods over
IEnumerable<T>andIQueryable<T>that filter, sort, or transform data. - The article says extension methods can make code easier to call, but they also hide where a method is actually declared.
