Extension methods allow you to add methods to existing types .And the interesting thing is that you can do it without adding this method or updating the original type.
To define and call extension methods consider the following points:
- Define a static class that contains the extension method
- Define the extension method as static method
- Add the first parameter with 'this keyword' upon which this extension method has to be operated on.
- If the calling class and the class which contains the extension method then add 'using' directive to specify the namespace which contains the extension method's class.
- Now you can call the extension method as it is the instance method of this type.
Example:
string s="My name is Usman";
s.Display(10); //Display this name ten times
Now the point is "Is there any Display method in string class ?The answer is no." But with extension method you can do it without updating the string class and even you can call this method with the instance of string class.
1.This is Class which contains the extension methods .Both class and extension method are with static and as we have to call this method on string so we would use 'this keyword for first parameter .
2.This is the calling class which calls the extension method .In this class you declare a string object 'name'. There is no Display method which can be called with the string object.But with the extension method you can do that.
Output:
No comments:
Post a Comment