May 28, 2008

Extension Methods in C# 3.0

Extension methods are static methods that can be invoked using instance method syntax. In effect, extension methods make it possible to extend existing types and constructed types with additional methods.
Note: Extension methods are less discoverable and more limited in functionality than instance methods. For those reasons, it is recommended that extension methods be used sparingly and only in situations where instance methods are not feasible or possible.
Extension members of other kinds, such as properties, events, and operators, are being considered but are currently not supported.
Lets see the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Features
public static class Extensions
public static int ToInt32(this string s)
return Int32.Parse(s);

class Program
static void Main(string[] args)
string strTest = "1";
Console.WriteLine(strTest.ToInt32()); //Will print 1

Now lets look close to the following statement
(this string s)

This means, method ToInt32 is applied to a variable which type is string.

So simple as that :)

Reand More on C# 3.0

No comments: