Search code examples
c#extending-classes

How do I extend the String class?


Extending core classes in javascript is dead easy. I get the impression it's not quite so easy in C#. I was wanting to add some things to the String class so that I could do stuff like:

string s = "the cat's mat sat";
string sql = s.smartsingleQuote();

thus giving me

the cat''s mat sat

Is that even feasible, or do I have to write a function for that?


Solution

  • Yes you can do this, with an extension method. It'll look something like that:

    public static class NameDoesNotMatter {
       public static string smartSingleQuote(this string s) {
          string result = s.Replace("'","''");
          return result;
       } 
    }
    

    The magic is the keyword "this" in front of the first argument. Then you can write your code and it'll work:

    string s = "the cat's mat sat";
    string sql = s.smartsingleQuote();