Extension Methods in C#

What are extension methods?

Extension methods in C# are used to extend the functionality of a class which is not provided by the class itself, without altering the definition of the original type. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.

Rules to Use Extension Methods

We need to import the namespace in which the static class is defined which contains the extension methods. Suppose I have defined my method in a class which is again defined under namespace. In that case, we need to include the namespace using the keyword using wherever we want to use the method.
C# only supports extension methods, it does not support extension properties, extension events, extension operators.
Extension methods must be declared in non-generic and static classes.
C# compiler looks only for the extension methods defined in static classes that are themselves defined at the file scope. In other words, if we define a static class in some class and then define our extension methods, in that case, we will get a compile time error as shown below.

Copyright © All Rights Reserved - C# Learners