Introduction
In this article, I will explain what extension method is, and why and where we should use this. Let’s understand the term extension. Extension means we are going to create something new with the help of old things or objects etc. So, this is a very predictable word in the real world. On the other hand, in the programming world, this means almost the same thing with some new enhancements.
Let’s see the professional definition in terms of OOPS.
Extension method is a special kind of static method which we can access throughout or outside of a program. Extension method helps us to extend the class with new methods without any changes in base type or class. We can create new methods in the dll library class also without changing the old code though extension method.
Let’s see the simple example of extensionmethod .
- using System;
- namespace csharpdemoexample {
- public static class csharpdemo {
- public static void Main() {
- try {
- Console.WriteLine(Myextmethod("Welcome", "Extension"));
- Console.Read();
- } catch (Exception ex) {
- throw ex;
- }
- }
- public static string Myextmethod(this string a, string b) {
- return (a + " " + b);
- }
- }
- }
All right. Now, one question shih might come to your mind is: "Why I have written this keyword in parameter?"
So, let me clarify this confusion. This keyword is required for first argument parameter, no matter what data type you use for this. But, this keyword is mandatory for extension method.
If you are not defining this, it will act like a normal static method.
Now, the next question is how to use the extension method in dll file. In other words, if you have created the dll in C#, all the classes and methods will act as private. Then, how we can use the same dll and create a new method inside our new application.
Let's add a Class library in our solution project.
Created two methods - Add and Subtract inside dll class. Now, I want to use this DLL into some project. Using this class, I want to create one new method, like multiply. So, we will achieve this by using extension method.
Add the DLL reference inside your project in which you want to implement the new method.
- using BaseDLL;
- namespace csharpdemoexample {
- public static class csharpdemo {
- public static int Multiply(this MathDemo obj, int a, int b) {
- return a * b;
- }
- public static void Main() {
- try {
- MathDemo obj2 = new MathDemo();
- Console.WriteLine("Result of extension method multiply is :" + Multiply(obj2, 10, 20));
- Console.Read();
- } catch (Exception ex) {
- throw ex;
- }
- }
- }
- }
Conclusion
Now, we are done. So, in this article, we have seen what extension methods are and how to create and use them.
Thanks for reading this article. Your comments and feedback are always welcome.