Pages

Search This Blog

Friday, August 12, 2016

Extension Methods in c#

 What is Extension Method

1. Extension method feature introduced in c# 3.0.
2. Extension of a method is a way to add some more methods as per requirement into an       existing library.
3. For Example in string we have methods like length(), split(), substring() etc. If we want that we should     have one more method that will count number of words in a string we can extends string methods by     adding one more method WordCount().

Properties of Extension Methods

1. It is a static method.
2.It must be in a static class
3. It uses "this" keyword as first parameter with a type in .NET.

Sum of Digits of a number using extension method

Step1. Very first we will create an extension method.


The above method takes and integer number as input and calculate the sum of its digit and returns sum of digits of the number.

Step 2. Now we are going to call this method from code like other inbuilt methods.














And we have created an extension method for int numbers and we have seen it can be call like other inbuilt method. 


Example Flow

















No comments:

Post a Comment