How is it possible to make prototype methods in C#.Net?
In JavaScript, I can do the following to create a trim method for the string object:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
How can I go about doing this in C#.Net?
You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.
You can, however, in C# 3.0, use extension methods, which look like new methods, but are compile-time magic.
To do this for your code:
public static class StringExtensions
{
public static String trim(this String s)
{
return s.Trim();
}
}
To use it:
String s = " Test ";
s = s.trim();
This looks like a new method, but will compile the exact same way as this code:
String s = " Test ";
s = StringExtensions.trim(s);
What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?
It sounds like you're talking about C#'s Extension Methods. You add functionality to existing classes by inserting the "this" keyword before the first parameter. The method has to be a static method in a static class. Strings in .NET already have a "Trim" method, so I'll use another example.
public static class MyStringEtensions
{
public static bool ContainsMabster(this string s)
{
return s.Contains("Mabster");
}
}
So now every string has a tremendously useful ContainsMabster method, which I can use like this:
if ("Why hello there, Mabster!".ContainsMabster()) { /* ... */ }
Note that you can also add extension methods to interfaces (eg IList), which means that any class implementing that interface will also pick up that new method.
Any extra parameters you declare in the extension method (after the first "this" parameter) are treated as normal parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With