C Sharp Extension method

C Sharp Extension method

23 May 2024
Intermediate
8.23K Views
6 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Extension method: An Overview

An extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering them. In the extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by the extension method. Conceptually, extension methods provide an implementation of the decorator's structural pattern. At compile time an extension method call is translated into an ordinary static method call. In this C# Tutorial, we will explore more about the C Sharp Extension method.

A Simple Extension Method Example

Let's elaborate on this in C# Compiler.
 //defining extension method
public static class MyExtensions
{
 public static int WordCount(this String str)
 {
 return str.Split(new char[] { ' ', '.', ',' }).Length;
 }
} 

class Program
{
 public static void Main()
 {
 string s = "Dot Net Tricks Extension Method Example";
 
 //calling extension method
 int i = s.WordCount();

 Console.WriteLine(i);
 }
}
 

output:

 6

Read More - C# Programming Interview Questions

Extension Methods Chaining

Like instance methods, extension methods also have the chaining capability.

 public static class ExtensionClass
{
public static string Pluralize (this string s) {...}
public static string Capitalize (this string s) {...}
}
//we can do chainig of above methods like as
string x = "Products".Pluralize().Capitalize(); 

Ambiguity, resolution, and precedence of extension method

To use an extension method, it should be in the same scope as the class. If two extension methods have the same signature,the more specific method takes precedence.

 static class StringExtension
{ // first method
 public static bool IsCapitalized (this string s) {...}
}
static class ObjectExtension
{
 // second method
 public static bool IsCapitalized (this object s) {...}
}
// code here
// first method is called
bool flag1 = "Dotnet-Tricks".IsCapitalized(); 
// second method is called
bool test2 = (ObjectHelper.IsCapitalized ("Dotnet-Tricks"));  

Key points about extension methods

  1. An extension method is defined as a static method but it is called an instance method.

  2. An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.

  3. An extension method having the same name and signature as an instance method will never be called since it has a lower priority than an instance method.

  4. An extension method couldn't override the existing instance methods.

  5. An extension method cannot be used with fields, properties, or events.

  6. The compiler doesn't cause an error if two extension methods with the same name and signature are defined in two different namespaces and these namespaces are included in the same class file using directives. The compiler will cause an error if you try to call one of the extension methods.

Benefits of extension methods

  • It allows existing classes to be extended without relying on inheritance or changing the class's source code.
  •  There is no concept of extending its functionality If the class is sealed. For this, a new concept is introduced, in other words, extension methods.
  • It is used for the dynamism of the C# enhancements in your class's design.
Summary

In this article, I try to explain the extension method and its various uses with examples. I hope after reading this article you will be able to use this trick in LINQ query. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article. Also, Consider our C# Programming Course for a better understanding of all C# concepts.

FAQs

Q1. What is extension method in C#?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. 

Q2. What are extends C# methods?

A C# extension method allows developers to extend the functionality of an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.

Q3. What is the extension method contains in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type .

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Generative AI For Software Developers Jul 20 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Jul 20 SAT, SUN
Filling Fast
06:00PM to 08:00PM (IST)
Get Details
Azure Master Class Jul 20 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this