Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I inherit the string class?

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.

like image 607
Nasreddine Avatar asked Dec 05 '11 17:12

Nasreddine


People also ask

Can we inherit string class?

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.

Can we inherit string class in Java?

It is not possible to directly inherit String class as it is final. Also wrapper classes java. lang.

What is string inheritance?

The ability to share function-string definitions among classes by creating relationships between classes is called function-string inheritance.

Why is string sealed?

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.


1 Answers

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) { } } 
like image 93
René Avatar answered Sep 17 '22 08:09

René