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 thisstatic 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 :
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
3 comments:
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 ??
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.
ok . thanks Geme .
Post a Comment