Now with C# 3.0 has provided with the concept of extension methods. Extension methods enable us to extend the functionality of data types already defined. No source code of the assembly is available to modify & recompile the assembly. Still one can extend the data types functionality.
Inheritance also provides capability to extend the functionality but the extended functionality is available only for derived classes & not to the base class. e.g Consider I'd like to have a ToInt function in String class. If I use inheritance approach, I have to create new derived type. So I cannot use methods of derived type on my String objects.
Extension methods are written in static class. The method should also a static method. First parameter of the method must be of type being extended. The first parameter must have this keyword before it.
See the code below.
Complex is the type defined as follows:
Use the method ToComplex for int or Int32.
Sealed classes can take advantage of extension methods. LINQ makes use of extension methods defined in Enumerable static class. The class extends functionality of objects implementing IEnumerable
interface. To use the extension methods from Enumerable class refer the assembly System.Core.