Friday, February 8, 2008

C# language enhancements in .NET 3.5 (Part 2)

If any one read my first article he will know that that's
the second part of the language enhancements in C# 3.5 if not
and that is what I'm sure of, so you know that now.
Let's continue our discussion directly.

- Extending types using Extension method
Extension method allows us to extend any type
without the need to sub-classing it,
in other words we can add more functionalities to types
to which we don't have the source code.

Example:

//this example will add another method to the string class
//this method will check if the string contains your name or not

public static class Extensions
{
public static bool IsMyNameHere(this string str)
{
if (str.Contains("your name"))
return true;
return false;
}
}

//in the main method we can use that by the following syntax
static class Program
{
static void main()
{
string str= "blah blah blah";
bool IsMyNameHere;

IsMyNameHere= str.IsMyNameHere();
IsMyNameHere= "another blah blah".IsMyNameHere();
}
}


As you can see in the previous example you can easily add a new method to a class that you don't have its source code you can here use the IsMyNameHere() method
the same way you use ToUpper() method. You can now easily extend that framework you use daily and use your own methods on someone else’s class.

Notice that to define your extension method you need some steps
1-a public static class that contains your extension methods
2-your extension method must be a static method
3-the first word in the parameters of your extension method should be this keyword
4-also the second word in the parameters of your extension method should be the name of the class which you extend or which you add this method to.

Extension methods can be added to any type, including the generic types such as List and Dictionary.
You can also create an extension method that takes any number of parameters.
//the signature of the method will be like that
public static bool IsMyNameHere (this string str,int i)
//you can use it like that
bool IsMyNameHere = str.IsMyNameHere(0);

I know this is very short post but that's because i'm very lazy and want to sleep now
keep smile and wait for the next thread in this series.

No comments: