Skip to main content

Extension methods in C#

Consider the class
Invoke the above from your form using

This will show “Hello” in message box.
Consider the scenario where you don’t have the access to the above code and you want to add another method to the above class.  That is where the C# feature of extension method is to be used.

Extension methods

Extension methods as the name implies, is about extending the functionalities of the class.  The Extension methods help you add a new method to the existing Class (or Type).
Now let us add the new method sayHI to the above testclass .  First create a new static class and name it as testExtension.  Remember that the extension method must be defined as static  method
Extension Methods in C#
Extension Methods in C#
Now you can use sayHI method  just like any other method as shown below.

C#
1
2
3
4
5
6
7
 
 
    testClass test = new testClass();
    MessageBox.Show( test.sayHello());
    MessageBox.Show(test.sayHi());

Few Important things to note


  1. Extension method must be defined as static method and must reside in a static class
  2. this keyword must be the first parameter of the extended method. This will actually inform the compiler that the method is an extension method.
  3. Extension method must be defined in the root of the namespace. It cannot be nested inside another class under the namespace
  4. The type that is being extended must be referenced in the extension method. Use the using statement to import the namespace.
  5. protected/private members of the type that is being extended will not be accessible from the Extension methods.
  6. You cannot override any method of the type you are extending.
  7. The Extension method has lower priority than the methods defined In the type.  Similar named method in instance, always executed rather than the extended method. In fact the extended method will never be called
  8. The Extension methods with the same name and signature may signature for the same class may be declared in multiple namespaces without causing compilation errors.
  9. Extension method cannot be used for adding a new properties, fields or events
 Benefits
  1. Extension methods appear under the intellisense.
  2. It makes the code more readable.
  3. Extend the functionality of third party libraries where you don’t have access to the code. ( This may also break your code if the third party vendor changes the implementation of the library)

Conclusion

Extension methods are nice little feature of c#.  LINQ is one module which uses extension methods extensively.

Comments

  1. Thanks for the blog. Looking forward for more info on C# and more technologies...

    ReplyDelete
  2. Really nice blog and it's very use full for beginners as well as exp. thanks mate for such a nice blog..keep it up...

    ReplyDelete
  3. Really nice blog and it's very use full for beginners as well as exp. thanks mate for such a nice blog..keep it up...

    ReplyDelete

Post a Comment

Popular posts from this blog

What is cookie? Advantages and disadvantages of cookies?

What is cookie? A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. If any web application using cookies, Server send cookies and client browser will store it. The browser then returns the cookie to the server at the next time the page is requested. The most common example of using a cookie is to store User information, User preferences, Password Remember Option etc.It is also one of the common and mostly asked interview questions. Some facts about Cookie Here are a few facts to know about cookies: · Cookies are domain specific i.e. a domain cannot read or write to a cookie created by another domain. This is done by the browser for security purpose. · Cookies are browser specific. Each browser stores the cookies in a different location. The cookies are browser specific and so a cookie created in one browser(e.g in Google Chrome

Code First Getting Started

In this tutorial let us create a simple application to demonstrate the use of entity framework using code first. We are using Visual Studio 2015 and entity framework 6.1.3. You can download Visual Studio community Edition . You should have the basic knowledge of .Net framework, C# and MS SQL Server. In this tutorial, we will create a simple application with a user class.  Our user class will have basic information like name and email address of the user. Create the Project Open Visual Studio. File ->New -> Project Select C# -> Select Console Application Name the application as “EFGettingStarted” Click on OK Install Entity Framework The next step is to install the Entity framework. This can be installed via nuget package console. Click on Tools->Nuget Package manager -> Package Manager Console and type the following command C# 1 2 3   install - package entityframework   This will install the late

First, FirstOrDefault, Single, SingleOrDefault In C#

For people who are new to LINQ, it is difficult to understand the difference between First, FirstOrDefault, Single, SingleOrDefault. In this blog, I will explain what to use and when.     I will take a simple example to make you understand practically how these methods work.   Consider a class Employee with properties as Id, Name, and Department. class  Employee {    public   int  Id {  get ;  set ; }    public   string  Name {  get ;  set ; }    public   string  Department{  get ;  set ; } } I have a list of Employees: List<Employee> employeeList =  new  List<Employee>(){    new  Employee() { Id = 1, Name =  "Sunny" , Department =  "Technical"  },    new  Employee() { Id=2, Name= "Pinki" , Department = "HR" },    new  Employee() { Id=3, Name= "Tensy" , Department = "Finance" },    new  Employee() { Id=4, Name= "Bobby" , Department = "Technical" },    new