Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Extension Method in C#
3.
Key Points
4.
Examples
4.1.
Code 1
4.2.
Code 2
5.
Frequently Asked Questions
5.1.
What is an Extension Method in C#?
5.2.
How to implement an Extension Method?
5.3.
Are Extension methods static in nature?
6.
Conclusion
Last Updated: Mar 27, 2024

Extension Method in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

The extension method concept in C# allows you to add new methods to an existing class or structure without modifying the original type's source code, requiring special permission from the original style, and recompiling the original type. In this article, we shall be learning more about the extension methods along with several important points related to this topic and a few examples explaining its application.

Extension Method in C#

Extension methods help you "add" approaches to existing types without creating a new derived type, recompiling it, or modifying it. Although extension methods are static, they are referred to as instance methods in the extended class. There's no discernible difference between calling an extension method and the procedures defined in a type in client code written in C#, F#, or Visual Basic.

The "this" modifier is used for the first C# extension method parameter, which is a static method of a static class. The extended type will be the type of the first parameter.

Extension methods are only in scope if you use a directive to import the namespace into your source code.

Also Read About - singleton design pattern in c#

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Key Points

The following key points must be kept in mind while using extension method.

  • A top-level static class must define an extension method.
  • Extension methods bear the same name and signature as instance methods aren't called.
  • Extension methods cannot override existing methods.
  • Fields, properties, and events are all excluded from extension methods.
  • The type for which the extension method is applicable must be the first parameter of the extension method, followed by this keyword.
  • Extension methods are always defined as static methods, but they become non-static methods once they are bound to a class or structure.
  • When an extension method has the same name as an existing method and the same signature, the compiler will print the current method rather than the extension method. In other words, method overriding is not supported by the extension method.
  • You can also implement new methods to the sealed class using the extension method concept.
  • Fields, properties, and events are not included.
  • It must be defined in the static top-level class.
  • Because multiple binding parameters are not permitted, an extension method can only have one binding parameter. However, you can specify one or more standard parameters in the extension method.

Examples

Now, let's go through some coding examples to see how can you use Extension Method in C# .

Code 1

using System;  
namespace CSharpFeatures  
{  
    public static class StringHelper  
    {  
        public static string GetUpperCase(this string name)  
        {  
            return name.ToLower();  
        }  
    }  
    public class ExtensionMethodExample  
    {  
        static string name = "CODING NINJAS";  
        static void Main(string[] args)  
        {  
            string str = name.GetUpperCase();    
            Console.WriteLine(str);  
        }  
    }  
}  

Output

coding ninjas

We have added an extension method GetLowerCase() in the C# String class in this example.

Code 2

using System;  
namespace CSharpFeatures  
{  
    public static class StudentHelper  
    {  
        public static string GetUpperName(this Student student) 
        {  
            return student.name.ToUpper();  
        }  
    }  
    public class Student  
    {  
        public string name = "coding ninjas";  
        public string GetName()  
        {  
            return this.name;  
        }  
    }  
    public class ExtensionMethodExample  
    {  
        static void Main(string[] args)  
        {  
            Student student = new Student();  
            Console.WriteLine(student.GetName());  
            Console.WriteLine(student.GetUpperName());  
        }  
    }  
}  

Output

coding ninjas
CODING NINJAS

In this example, we have added an extension method to a Student class.

Frequently Asked Questions

What is an Extension Method in C#?

The extension method is a particular case of the static method defined inside a static class whose first parameter is the type of the operator it will operate on with a prefix this keyword. The extension methods can be included in .NET framework classes, custom classes, structs or interfaces, and third-party classes.
 

How to implement an Extension Method?

If an extension method consists of the same signature as a type method, it will never be called. At the namespace level, extension methods are brought into context.
 

Are Extension methods static in nature?

Extension methods are static methods, but they are referred to as instance methods in the extended type. There is no distinguishable difference between calling an extension method and the methods defined in a type in client code written in C#, F#, or Visual Basic.

Conclusion

In this article, we have covered the topic of the Extension Method in C#. We have briefly introduced the subject along with crucial points. We also discussed the code examples with their output and results. 

Related links:

With our Coding Ninjas Studio Guided Path, you may learn about  Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more. Check out the mock test series and the competitions on Coding Ninjas Studio if you want to put your coding talents to the test! Check out the problemsinterview experiences, and interview bundle for placement preparations if you're just getting started and want to see what questions large companies like Amazon, Microsoft, and Uber ask.

Interested in ready more similar topics? Check out  C# interview questions for 5 years Experience.

We hope this blog has aided you in broadening your horizons. Please give this article a thumbs up if you enjoyed reading it.

Live masterclass