Home » Tutorials » C# » Extension Method in C#

Extension Method in C#

Reflection Introduction c#
MSDTC on server 'PC-Name' is unavailable.

Extension Method in C#

I have already explained  Reflection Introduction c#Insert data into Database table using SQLBulkCopy class in C#as keyword C#, Import/Upload Excel file in asp.net with C#The Microsoft Jet database engine cannot open the file. It is already opened exclusively by another user,   Call method after specific time interval C#Alert from code behind asp.net,required field validator in asp.net,Difference between RegisterClientScriptBlock and RegisterStartupScript asp.netDifference between ref and out parameters.

An Extension method is used to extend existing class, the method must be static.

To define Extension method, we have to follow below steps:

  1. Define class with Static
  2. Define Method using static and method’s first parameter followed by “this” keyword.

Lets have a look into how could we create and consume Extension Method in C# by example:

OUTPUT:

Extension Method in C#

Extension Method in C#

As explain in example, we have declared “MyExtensionClass” static class in which we have declared static method, which will be used as extension method of string.  We are extending C# string to convert first latter of string in Capital.

You have noticed in code that inside method, I have declared parameter with “this” keyword and declare method with static. By this we could directly use “strFirstLatterUpper” method directly as Extension method of string. We can call that method directly as shown below:

Advantages of Extension Method in C#?
  1. Re-usability of code
  2. Maintainable code
  3. Clean and readable code in LINQ query.
Disadvantages of Extension Method in C#?
  1. There is no compilation error or warning, if you would have Extension method and Regular method with same class or context.

About

Hello friends, My self Dhruv Sheth, I have more than 6 years of Industrial experience as a Software Developer. In my career I got chance to work with asp.net, c#,Web API, JavaScript, JQuery, WPF, WCF , Windows Application, PostScript, vb.net, GhostScript etc. So I have decided to share my knowledge with everyone and finally I have come up with TechnoThirsty.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Time limit is exhausted. Please reload CAPTCHA.




DISCLAIMER:
The content is copyrighted to technothirsty.com and may not be reproduced on other websites without permission from the owner.You may contact us using the information below.