Extension Methods

Extension Methods

An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable type such as List or Array.

Feature and Property of Extension Methods

The following list contains basic features and properties of extension methods:

• It is a static method.

It must be located in a static class.

It uses the "this" keyword as the first parameter with a type in .NET and this method will be called by a given type instance on the client side.

It also shown by VS intellisense. When we press the dot (.) after a type instance, then it comes in VS intellisense.

An extension method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement.

You can give any name for the class that has an extension method but the class should be static.

If you want to add new methods to a type and you don't have the source code for it, then the solution is to use and implement extension methods of that type.

If you create extension methods that have the same signature methods as the type you are extending, then the extension methods will never be called.


Extension Methods
added 10 years 2 months ago

- How to make bold the text before colon character in Microsoft Word
- Generate object from xml in c#
- 24 Useful Distinct Color Codes
- How to draw an arrow with DrawLine command
- How to write Snake game in C#?
- Break Parallel Foreach Earlier
- How to find all Stored Procedures having a given text inside
- How to Create and Write Excel File in C#
- Extension Methods
- Microsoft Code Contracts
- VersaFix
- QuickFIX
- fix4net
- Converting String to Double in C#
- C# File Operations, C# Input Output (C# I/O)
2
1