Introduction
This article explains Extension methods, a new existing feature of C# 3.0. This feature is available in 3.0 and higher versions of C#. An Extension method is very important and very special for programming developers.
An Extension method is special for the class design.
Why we need Extension Methods
Using an Extension method we can use another class method without changing functionality. But it is very compulsory that an Extension method be defined in a top-level static class.
Generally in our programming we saw that there are two classes, a parent class and a child class in our program. The child class inherits the method of a parent class. it can change the functionality of the parent class method.
But in an Extension method it must not be required to change the functionality of another method without having a sub class. A drawback exists in extension methods, they cannot be used to override an existing method.
Specification of an Extension Method
An Extension method is a very cool and new feature. We can say this is an instance method. This Extension method is a Static method of a static class. This allows us to add a new method for a predefined method. It increases the functionality of a predefined method.
An Extension method can use another method without inheritance and without changing the source code. In the Extension method we are using the "this" modifier. It is applied as the first parameter and the parameter extends the functionality of this method without changing a parent class method.
Example of extension Method
- public static class Extensionmethod
- {
- public static double countTex(this Book b)
- {
- return (b.bookPrice * .25);
- }
- }
- }
Full code of extension Method
- namespace ConsoleApplication1
- {
- using BOOKS;
- class Program
- {
- static void Main(string[] args)
- {
- List<Book> BOOKS = new List<Book>()
- {
- new Book{BookName = "C-sharp", bookPrice = 450},
- new Book{BookName = "SQL-server", bookPrice = 750},
- new Book{BookName = "VB 2008", bookPrice = 500}
- };
- foreach (Book b in BOOKS)
- {
- Console.WriteLine("{0} costs {1} (Tex: {2})", b.BookName, b.bookPrice, b.countTex());
- }
- }
- }
- public static class Extensionmethod
- {
- public static double countTex(this Book b)
- {
- return (b.bookPrice * .25);
- }
- }
- }
-
- namespace BOOKS
- {
- public class Book
- {
- public string BookName { get; set; }
- public double bookPrice { get; set; }
- }
- }
Output