Add Methods to Built-in Classes in C#
Consider, you are writing a program where you work with the arrays, lists. Let’s say you need to check if the list is empty or not. What would you do ?
Code Without Extension Method
Probably, if you do not know about the extension methods, you would write something like this:
List<int> list = new List<int>();if (list.Count == 0) {
// Do somethings beautiful
}
Code After Writing Extension Method
Would not it be better if we would write code like this:
List<int> list = new List<int>();if (list.IsEmpty()) {
// Do somethings beautiful
}
This definitely would be helpful. So, let’s see how we can do it:
Writing Extension Method
I am going to create a class for only extension methods. This is not required, but it would be much easier to reuse and maintain the code.
public static class ListExtension
{
public static bool IsEmpty(this List<int> list)
{
return list?.Count == 0;
}
}
First of all, this class should be static and non-generic.
Note: Non-Generic means that we cannot write a generic type like this:
public static class ListExtension<MyType>
{
}
How Does It Work ?
Although we make these extensions methods static, they actually will not be static. Instead, they will be used as instance methods. I will give an example in a minute.
When a List<int>
instance calls IsEmpty()
method, that instance will be sent as a parameter to this method. this
keyword tells the compiler to recognize IsEmpty()
method as the built-in List<int>
class’ method.
Then, we have a return list?.Count == 0
which first checks if the list is null or not (with ? operator, you can read more here) and return a boolean that indicates if the list’s item count is 0 or not.
Example
In this example, we have created a list with three items in it. When we call IsEmpty()
method, the output is false obviously.
public class Program
{
public static void Main(string[] args)
{
List<int> list = new List<int>() { 1, 2, 3 };
Console.WriteLine(list.IsEmpty()); // outputs false }
}
If you are reading this sentence, then it means that you have read the whole article and have a good understanding of extension methods.
I hope it was helpful for you and see you in the next articles :).