How Can I inherit the string class?

32,842

Solution 1

System.String is sealed, so, no, you can't do that.

You can create extension methods. For instance,

public static class MyStringExtensions
{
    public static int WordCount(this string inputString) { ... }
}

use:

string someString = "Two Words";
int numberOfWords = someString.WordCount();

Solution 2

Another option could be to use an implicit operator.

Example:

class Foo {
    readonly string _value;
    public Foo(string value) {
        this._value = value;
    }
    public static implicit operator string(Foo d) {
        return d._value;
    }
    public static implicit operator Foo(string d) {
        return new Foo(d);
    }
}

The Foo class acts like a string.

class Example {
    public void Test() {
        Foo test = "test";
        Do(test);
    }
    public void Do(string something) { }
}

Solution 3

If your intention behind inheriting from the string class is to simply create an alias to the string class, so your code is more self describing, then you can't inherit from string. Instead, use something like this:

using DictKey = System.String;
using DictValue= System.String;
using MetaData = System.String;
using SecurityString = System.String;

This means that your code is now more self describing, and the intention is clearer, e.g.:

Tuple<DictKey, DictValue, MetaData, SecurityString> moreDescriptive;

In my opinion, this code shows more intention compared to the same code, without aliases:

Tuple<string, string, string, string> lessDescriptive;

This method of aliasing for more self describing code is also applicable to dictionaries, hash sets, etc.

Of course, if your intention is to add functionality to the string class, then your best bet is to use extension methods.

Solution 4

You cannot derive from string, but you can add extensions like:

public static class StringExtensions
{
    public static int WordCount(this string str)
    {
    }
}

Solution 5

What's wrong with a helper class? As your error message tells you, String is sealed, so your current approach will not work. Extension methods are your friend:

myString.WordCount();


static class StringEx
{
    public static int WordCount(this string s)
    {
        //implementation.
    }
}
Share:
32,842
shraysalvi
Author by

shraysalvi

Updated on June 11, 2020

Comments

  • shraysalvi
    shraysalvi almost 4 years

    I want to inherit to extend the C# string class to add methods like WordCount() and several many others but I keep getting this error:

    Error 1 'WindowsFormsApplication2.myString': cannot derive from sealed type 'string'

    Is there any other way I can get past this ? I tried with string and String but it didn't work.