Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a method applicable to a String object

Tags:

c#

inheritance

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
        // ...
    }
}
like image 643
Otiel Avatar asked Jan 17 '26 20:01

Otiel


1 Answers

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.

like image 79
jason Avatar answered Jan 20 '26 11:01

jason