Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Visual C# » Secrets of Extension Methods: Part I

Secrets of Extension Methods: Part I

This article gives an introduction to Extension Methods.

Author Rank :
Page Views : 7413
Downloads : 76
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ExtensionMethods.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Most of us are familiar with C# new feature Extension methods. But, in this article I am going to discuss detailed implementation and restrictions on Extension Methods. I designed this application in Visual Studio 2008 using Console Applications.

Introduction:

Extension methods allows us to define new methods on existing types, which can be either .NET type or user defined class. We can define new methods without extending or deriving existing type. Internally, extension methods are treated as class or static methods. But, it will be called on instance of a class.

Use of Extension Methods in .NET Framework:


Extension methods are used heavily in most of the new .NET Classes [BCL]. LINQ uses this feature in its implementation. In coming articles, we will see how LINQ implements this feature.

Steps to create a sample Extension Method:

  1. Create a new Console Application and name it as ExtensionMethods. Add a class to it and name as Extensions.cs
     
  2. Make class as a public. Most of the cases, public visibility is better.
     
  3. Create a new method and name it as InitCap. This method takes a string as a input and makes first letter as Uppercase and returns complete string back.
     
  4. Make visibility as public and static in nature for the method.
     
  5. For Extension Methods, first parameter will be always the instance calling that method. So, we no need to pass it explicitly. It will be preceded by keyword this. The type of first parameter specifies on what kind of instances, this method is available.

    So, first parameter implies following things: 
    1. It should be preceded by keyword this.
       
    2. Its type specifies on what kind of objects, this method is available.
       
    3. No need to pass this parameter, when calling the extension method explicitly.
  6. Write this lines in InitCap method:

value = value[0].ToString().ToUpper()+value.Substring(1,value.Length-1);
return value;

This will make first letter capitalized and returns it back.

Finally, this class looks like this:



From this definition, we can say this method returns string and can be called on string objects [based on first parameter type].

Next go to program class and include the namespace in which the method is defined.
In this sample, no need to include the namespace. Since, both the client [program] code and extension methods are defined in same namespace.

So, create a string object and read the contents from console and call this extension method InitCap on that string object. Later, display the contents.

Finally, the program class will be like this:



Here, we called InitCap on the instance of string. So, it's easy to understand and improve readability of the code by using Extension Methods. We are calling InitCap without any parameters, since first parameter will be the object [input]

Even though, we called this method as an instance method. Internally, it will treat as a static method.

Restrictions:

If there is an already existing method with same signature as extension method in a type. Than, extension method will be ignored and never called.

First, it looks for inbuilt method. If it won't find a match, it will look for extension method. If it is not there, it will throw an error.

Internal Implementation:


If we disassemble this code, we can see the call to extension method will be like this:

Call string ExtensionMethods.Extensions::InitCap(string)

This will call InitCap method present in Extensions Class.

Summary:

An extension method allows us to add new method on any type without redefining or deriving it. Create a static class and static methods with first parameter preceded by keyword this. Include the namespace in the client code and call it.

I am attaching the code for reference. I hope this will be useful for all.

Part 2

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sateesh Arveti
I hold Bachelors degree in Computer Science along with MCSD,MCTS and MVP for the year 2009. Areas of Interest: C#, WPF, WF, silverlight, ASP.NET, Oracle and SQL Server.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.