FCI-Helwan blog

Just another FCI-H weblog

What’s new in C# 3.0 ? Part 2

Consider the following , iam working in a project and i made a class and i made a simple method inside this class after small period i wanted to modify or add something in this method all what i have to do just back to the code of this function and modify its code , this is good

but what if this Method was in dll or was in a sealed class or i wanted to add method in a class of the primitive data types ? what can i do ?? the Extension Method was the Solution.

eg.. i want to add a small Method to the string type which return the second word in a given string
it will be like this

static class beta
{
public static string GetSecondWord(this string input)
{
string y="";
int count = 0;
bool flag = false ;
foreach (char c in input)
{
if (c == ' ')
{
flag = true;
count++;
}
if (flag == true && count == 1)
{
if( c != ' ')
y += c;

}
}
return y;
}
}


Notes :
  1. Make sure that the class is static
  2. Add this keyword before the type of the argument you want to extend.

so now you can write this code,

string x = “some string value”;
string y = x.GetSecondWord();

That’s it.
See you in the Next Part isA

Advertisements

February 10, 2007 - Posted by | C#

3 Comments »

  1. I am interesting to this series Gemo 🙂 .
    so I have question :
    How Beta class joined to string class !!!!!
    why joined with string class not X class as example ??

    Comment by Ahmed Essawy | February 10, 2007 | Reply

  2. hi Essawy ,
    Read The Note Num2 Carefully (Add this keyword before the type of the argument you want to extend. ) i extended the string Class in the prev. eg. about how Beta Class Joined the string Class .. this is the job of extension Method.

    Comment by Mohamed Gamal El-Den | February 10, 2007 | Reply

  3. ok . thanks Geme .

    Comment by Ahmed Essawy | February 10, 2007 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: