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.
The string class is marked sealed because you are not supposed to inherit from 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.
It is not possible to directly inherit String class as it is final. Also wrapper classes java. lang.
The ability to share function-string definitions among classes by creating relationships between classes is called function-string inheritance.
String is sealed mainly because it is immutable and CLR widely uses that feature (interning, cross-domain marshaling). If string would not be sealed then all CLR expectations on string immutability would not cost a dime.
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) { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With