|
|
|
|
|
|
Author Rank:
|
|
Total page views :
5719
|
|
Total downloads :
57
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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:
-
Create a new Console Application and name it as ExtensionMethods. Add a class to it and name as Extensions.cs
-
Make class as a public. Most of the cases, public visibility is better.
-
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.
-
Make visibility as public and static in nature for the method.
-
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:
-
It should be preceded by keyword this.
-
Its type specifies on what kind of objects, this method is available.
-
No need to pass this parameter, when calling the extension method explicitly.
-
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
|
|
|
Login
to add your contents and source code to this article
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
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.
|
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
|
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today. With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications. Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|