DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Batch Request Processing With API Gateway
  • Measuring Service Performance: The Whys and Hows
  • Guide To Selecting the Right GitOps Tool - Argo CD or Flux CD
  • Reducing Network Latency and Improving Read Performance With CockroachDB and PolyScale.ai

What Is the Extension Method in C#?

An overview of Extension Methods in C# and a step-by-step instruction on how to write one.

Dhanajay Kumar user avatar by
Dhanajay Kumar
·
Jul. 06, 16 · Tutorial
Like (2)
Save
Tweet
Share
5.43K Views

Join the DZone community and get the full member experience.

Join For Free

i often get questions about the extension method in c#. the extension method was introduced in c# version 3.0. and allows us to add functionalities in an existing class without modifying, extending, or re-compiling it.

essentially, the extension method allows us to add a new method to an existing class:

  • without modifying it or adding code
  • without extending it or creating a new derived type
  • without recompiling the class

extension methods are a special kind of static method but can be called on objects like an instance method. so an extension method can be used in the same way as normal instance methods.

steps to create an extension method

step 1: define a static visible class which will contain the extension method or extension methods. make sure the class is visible to the client code by applying the appropriate accede modifier.

step 2: create a static method with at least the same visibility level as the containing class.

step 3: the first parameter of the extension method always specifies the type method operates on. make sure the type name is preceded with the “this” modifier.

step 4: in the calling code, add the namespace that contains extension method class.

step 5: use the extension method on the type in the same instance method can be used. keep in mind that we do not need to pass the first parameter because that denotes the type, however we should pass the second parameter onwards to call the extension method.

let’s create an extension method!

let's go ahead and create an extension method for the string class. the string class does not have any wordcount method. we start by creating a console application project and then add a class to the console application project. we’ll name the class stringextension .

once the class is created, we have to perform the steps as discussed earlier:

  1. make the class static and public in this case.
  2. add a static method.
  3. since the class is public, make the method public too.
  4. pass the first parameter of the static method as the name of the class preceded with keyword “this”.
  5. write the code inside method to implement functionality:
namespace extensionmethoddemo
{
    public static class stringextension
    {
        public static int wordcount(this string s)
        {
            int count = 0;
            for (int i = 0; i < s.length; i++)
            {
                if (s[i] != ' ')
                {
                    if ((i + 1) == s.length)
                    {
                        count++;
                    }
                    else
                    {
                        if (s[i + 1] == ' ')
                        {
                            count++;
                        }
                    }
                }
            }
            return count;
        }
    }
}

in the above code listing, we have created an extension method to count the number of words in a given string. you may notice that:

  1. the stringextension class is a public static class.
  2. the wordcount method is a public static method.
  3. the first parameter in the wordcount method is a string because we are creating wordcount as an extension method of string class.
  4. the first parameter type string is preceded with the keyword “this”.

before using the extension method, let us compile the project. to do so, we need to perform the following steps:

  1. add dll to client project, if we have created extension method in different library.
  2. add namespace of the extension method class with using directive.
  3. use extension method as normal instance method.

we can use the newly created extension method as shown in the listing below:

using system;

namespace extensionmethoddemo
{
    class program
    {
        static void main(string[] args)
        {
            console.writeline("enter a senetence");
            string inputstr = console.readline();
            int numberofword = inputstr.wordcount();
            console.writeline(numberofword);
            console.readkey(true);
        }
    }
}

as we notice in the above listing, the extension method wordcount is used to count the number of words in a sentence. visual studio also shows the extension methods in intellcense, by appending the word extension next to the method name as shown in the image below:

as we see, we can use an extension method in the same way as any instance method. there could be a scenario where we have an instance method and an extension method with the same name and signature. in that case, an instance method always has more priority over the extension method. there are a few important points we should keep in mind about the extension method:

  1. it has lesser priority than the instance method, so if a class has an extension method and an instance method with the same name and signature, the instance method has priority.
  2. if an extension method conflicts with a member method of target type, the member method is always invoked instead of the extension method.
  3. the extension method can only access private members of the target type.

extension methods are very useful to add functionality in an existing class. many linq functions are implemented as extension methods. i hope the information provided here will help you in your projects, and thanks for reading!

Extension method csharp

Published at DZone with permission of Dhanajay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Batch Request Processing With API Gateway
  • Measuring Service Performance: The Whys and Hows
  • Guide To Selecting the Right GitOps Tool - Argo CD or Flux CD
  • Reducing Network Latency and Improving Read Performance With CockroachDB and PolyScale.ai

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: