I would like to create a method applicable to a String object, that will return a modified String:
String s = "blabla";
String result = s.MyNewMethod();
I have tried to create a new class String but keyword this seems unknown:
class String {
public String MyNewMethod() {
String s = this.Replace(',', '.'); // Replace method is unknown here
// ...
}
}
You need to define an extension method:
public static class StringExtensions {
public static string MyNewMethod(this string s) {
// do something and return a string
}
}
Note that extension methods are static and are defined in a static top-level class.
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