Example for extension methods in C#

Today I found one real world example for using extension methods in C#.

Maybe you know this code snippet from your own code:
If(object != null)
MessageBox.Show(„Value:“ + object.ToString().Trim());

I think it looks way to complex, for this stupid task.
Now lets write a extension method which checks for us

=> if the object is null return an empty string

=> if the object is a whitespace string return an empty string too

=> if the object is a normal string, returns it but with a automated trim() to remove annoying white spaces.

How to achieve that:

1. Create a public static class called „StringOptimizer“ and then create the function ToStringIntelligent.

public static class StringOptimizer
public static string ToStringIntelligent(this object _object)
if (_object == null)
return string.Empty;
return _object.ToString().Trim();

See the extension in the parameter _object. You use this before parameter declaration, that’s all.

Now to call this function your just do this:
Console.WriteLine("Value:" + item.ToStringIntelligent());
Note, no validation have to happen here, cause we do it in the extension method already. Extra plus is, that this method actually works with all types that derives from object, so you can use it with your string variables as well. Of course, we could use string.IsNullOrEmpty() function from the .NET framework, but I like to do the validation in just one method, instead of writing validation code for all string objects manually.

Another example is here on codeproject

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind markiert *

acht + 6 =