How to add my own Method to existing class?

  • Thread starter Thread starter Matt Doggie
  • Start date Start date
M

Matt Doggie

In C#, the String class has a lot of Methods, such as "mystring".Trim();

I want to add my own Method so that the whole web application can use it.
What I want is:

"mystring".GetIt();

How do I do it? How do I override the String class so that the whole
application knows about the change? I don't think just creating a new class
which inherits from String class would work, right?

Thanks..
 
Matt Doggie said:
In C#, the String class has a lot of Methods, such as "mystring".Trim();

I want to add my own Method so that the whole web application can use it.
What I want is:

"mystring".GetIt();

How do I do it? How do I override the String class so that the whole
application knows about the change? I don't think just creating a new class
which inherits from String class would work, right?

Indeed it wouldn't, and you can't do that anyway as String is sealed.

You can't add methods to existing classes in .NET.
 
You cannot do it by subclassing the String class (it is sealed and even if
it was not, strings would be instantiated in System.String, not in your
class).
All you can do is create a helper class with static methods:

class MyHelper {
public static string GetIt(string str) { /** your stuff here **/ }
}

you call it as MyHelper.GetIt("mystring");

Bruno.
 
Back
Top