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:
Er
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();
You cannot derive from string, but you can add extensions like:
public static class StringExtensions
{
public static int WordCount(this string str)
{
}
}
The string class is marked sealed
because you are not supposed to inherit from it.
So no, you can't "get around it".
What you can do is implement those functions elsewhere. Either as plain static methods on some other class, or as extension methods, allowing them to look like string members.
But you can't "get around" it when a class is marked as sealed.
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.
You can't inherit a sealed class (that's the whole point of it) and the reason why it wouldn't work with both string
and System.String is that the keyword string
is simply an alias for System.String
.
If you don't need to access the internals of the string class, what you can do is create an Extension Method, in your case :
//note that extension methods can only be declared in a static class
static public class StringExtension {
static public int WordCount(this string other){
//count the word here
return YOUR_WORD_COUNT;
}
}
You still won't have access to the private methods and properties of the string class but IMO it's better than writing :
StringHelper.WordCount(yourString);
That's also how LINQ works.
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) { }
}