Labels

Tuesday, April 29, 2008

Extension Methods - Orcas C# New Features

Hi,

This blog post summarizes the new features of C# langauge shipped with Orcas (VS 2005).

Below are the new features been introduced.

§ Automatic Properties

§ Object Initializers

§ Collection Initializers

§ Extension Methods

§ Lambda Expressions - p => expressions

§ Query Syntax

§ Anonymous Types

· Concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.

· Particularly useful when querying and transforming/projecting/shaping data with LINQ.

§ Var Keyword


Extension Methods

"Orcas" introduces a new concept ‘Extension methods’. It allows to do below.

§ Allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.

§ Help to blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

§ Enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework that is being introduced with .NET as part of the "Orcas" release.

§ Eligible for compile-time checking of all Extension Method usage - meaning you'll get a compile-time error if you mis-type or mis-use one.

Noramally we check to see whether a string variable is a valid email address, probably calling a separate class (probably with a static method) to check to see whether the string is valid. For example, something like:

string email = Request.QueryString["email"];

if ( EmailValidator.IsValid(email) ) {

}

Using the new "extension method" language feature in C# and VB, I can instead add a useful "IsValidEmailAddress()" method onto the string class itself, which returns whether the string instance is a valid string or not. I can then re-write my code to be cleaner and more descriptive like so:

string email = Request.QueryString["email"];

if ( email.
IsValidEmailAddress() ) {

}

How did we add this new IsValidEmailAddress() method to the existing string type? We did it by defining a static class with a static method containing our "IsValidEmailAddress" extension method like below:

public static class ArunManglickExtension
{
public static bool
IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}

Things to note:

§ See how the static method above has a "this" keyword before the first parameter argument of type string.

§ This tells the compiler that this particular Extension Method should be added to objects of type "string".

§ Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.

§ To add this specific Extension Method implementation to string instances within my code, simply use the ‘using’ statement.

More Complex Use:

· Above describes how Extension Method to be applied to individual types.

· Extension Methods can also be applied to any parent base class or interface within the .NET Framework. This enables developers to build a variety of rich, composable, framework extensions that can be used across the .NET Framework.

For example - To check whether an object is already included within a collection or array of objects, can be defined as below.

public static class ArunManglickExtension

{

public static bool In(this object s, IEnumerable c)

{

foreach (object obj in c)

{

if (obj.Equals(s))

{

return true;

}

}

return false;

}

}

this object s - Indicates that this extension method should applied to all types that derive from the base System.Object base type - which means I can now use it on every object in .NET.

The "In" method implementation above allows me to check to see whether a specific object is included within an IEnumerable sequence passed as an argument to the method. Because all .NET collections and arrays implement the IEnumerable interface, I now have a useful and descriptive method for checking whether any .NET object belongs to any .NET collection or array.

Testing the above code:

public static bool Test()

{

String[] strArray = new String[] { "India", "America", "Japan" };

String search = "Mumbai";

if(search.In(strArray))

{

return true;

}

return false;

}

Note: Because the CLR supports automatic boxing/unboxing of value-classes, extensions methods can be applied on numeric and other scalar datatypes directly.

"Arun".In(strArray);

Using Build-In LINQ Extension Methods:

LINQ itself has few build in Extension Methods. To check few example check the post here.

Reference: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead

No comments:

Post a Comment