Extension for Cleaner Code

The extension method in C#, VB, or F# is a static method that accepts this modifier of TInput. The method can be either void or return value. From MSDN definition, Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, F#, and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

In one of the chapters of Clean Code from Robert C. Martin, he said about using extension can improve the readability of the code and this concept has stuck into my head lately. For example, if you see this snippet of a code:

var report = GetReport();
var header = GetHeader;
var result = Add(report, header);

In the code snippet above, even the code quite simple, but it will still lead to ambiguity. Does the report object being add with the header object? Or is the header object being added with the report object? The intention of the program will be clear and straightforward.

var report = GetReport();
var header = GetHeader();
var result = report.Add(header);

In C# is very easy to make the extension. We just make the modifier as public static follows by a void or return type. Then using this modifier and the type of the object.

Extension examples:

public class Extension 
	public void Add(this Money amount, decimal value)
		amount.Value += value;
	public decimal GetValue(this Money amount) 
		return amount.Value;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.