Otiel
Otiel

Reputation: 18743

Create a method applicable to a String object

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
        // ...
    }
}

Upvotes: 2

Views: 68

Answers (2)

albertjan
albertjan

Reputation: 7817

I think this needs a bit more explanation.

  1. String is a sealed class in .NET as in most OO typesafe languages. This means you can't subclass string. Here's some great info about strings: http://www.yoda.arachsys.com/csharp/strings.html. And why they can't be subclassed.

  2. To make a subclass in .net you have to use the following syntax:

    // here "Test is a subclass of Test2"
    public class Test : Test2 {
    
    }
    
  3. Extension methods as mentioned by Jason are great for adding functionality to sealed classes. Extension methods can never override a function that already exists in a class. At compile time they have a lower priority then instance methods. Since extension methods do not live within the class they cannot access internal and private fields.

Upvotes: 1

jason
jason

Reputation: 241641

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.

Upvotes: 8

Related Questions