Extension methods are static methods behaving like instance methods. We generally use this so that we can use this function as a part of that object. In this article I will show you by creating the Null Checking Extension on C# on string types. I have taken this null checking extension in string because it is easy to understand. I bet you will love this extension method and will give you a head start if you want to create a complex one.
Lets create the static class named as “StringExtensions”
public static class StringExtensions
{
// Some codes here
}
Now lets add a function that returns empty if the string is null. Of course the function will be static because the class is static, right?
public static string EmptyIfNull(this string text)
{
return text ?? String.Empty;
}
And lets add another one as well that will return null if the string is empty.
public static string NullIfEmpty(this string text)
{
return String.Empty == text ? null : text;
}
Compiling together everything
public static class StringExtensions
{
public static string EmptyIfNull(this string text)
{
return text ?? String.Empty;
}
public static string NullIfEmpty(this string text)
{
return String.Empty == text ? null : text;
}
}
Usage
string nullString = null;
string emptyString = nullString.EmptyIfNull();// will return ""
string anotherNullString = emptyString.NullIfEmpty(); // will return null
Don’t forget the namespace at the top! I know you will figure that out by yourself. I hope you know now. Good luck and Happy Coding! 🙂