Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why don't we create a static class with a static method and then call that method to pass in a argument like this :

C#
 public static class A{
   public static void ToUpperString(string param)
   {
      param.ToUpper();
   }
}


instead of creating an Extension Method

C#
 public static class A{
   public static void ToUpperString(this string param)
   {
      param.ToUpper();
   }
}


What is the difference between these method call :

C#
string myString = "HelloFromVietnam";

string result1 = A.ToUpperString(mystring);
string result2 = mystring.ToUpperString();


==========================

This question makes me so excited. But I still have not figured it out. Waiting for your helps. :)
Posted

1 solution

Because Extension methods allow you to "extend" a sealed class by adding methods that look like they are part of the original class.

That makes them more readable when you use them in your code: as you show in your example.
Except...your example wouldn't work, and wouldn't do anything, or even compile! What you meant to say was probably:
C#
public static string ToUpperString(string param)
{
   return param.ToUpper();
}

And
C#
public static string ToUpperString(this string param)
{
   return param.ToUpper();
}
 
Share this answer
 
Comments
Benjamin Nguyễn Đạt 25-Mar-14 5:27am    
Oops...Thanks for correcting !
I know that extension method helps you to extend sealed class,dll..
But I do not see the differences between them. Why do I have to create an extension method when I could just create a static class
OriginalGriff 25-Mar-14 5:45am    
You don't "have to" - it's just a different way to do it, that can result in more readable code, is all.

It's just a syntactic sugar in the end: they both do the same thing.
But with an extension method you can say:
string s = myString.Substring(5, 10).ToUpperString().Trim();
rather than:
string s = A.ToUpperString(myString.SubString(5, 10)).Trim();

With the extension method it flows more easily to the eye - you can see immediately that the Substring is done first, then the ToUpperString, and finally the Trim.
With the static method version you have to look harder to work out what exactly is happening, although the same operations happen in the same order.
Benjamin Nguyễn Đạt 25-Mar-14 6:03am    
Thank you for your time! I can't thank you enough. cheer! :)
OriginalGriff 25-Mar-14 6:17am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900