2

I don't like the way string behaves and there are a few other things I would like to change.

It appears string cannot be extended because it is a sealed class.

Is there another way? I could copy the source code and make my own class but then it wouldn't be compatible with string, or could I make it compatible?

qwerty qwerty
  • 147
  • 1
  • 6
  • 2
    What sort of features are you after? You could use Extension methods to provide extra behaviors to string types but it would be interesting to know what you expect it to behave like. – tbddeveloper Jul 23 '15 at 18:31
  • You can't extend a sealed class. You can define some extension methods, of course, but this is far from "extending" the class. The answer to your question depends entirely on what exactly you don't like and you want to change. But most likely, it'll be best if you declare a new class that contains a string but offers different operations. – Theodoros Chatzigiannakis Jul 23 '15 at 18:43
  • 1
    I doubt you could copy source code either - the compiler does many special things with `string` (e.g. interning) that could not be replicated with source code. – D Stanley Jul 23 '15 at 18:45
  • What specific behavior(s) do you not like? – D Stanley Jul 23 '15 at 18:46
  • Standard way (using extension methods) is covered in linked duplicate. If your needs go beyond that - make sure to update the post with clarification like "I know I can use XXXX, but it does not give me way to do YYY. I tried ZZZ but it sucks". – Alexei Levenkov Jul 23 '15 at 19:01

1 Answers1

5

You could use extension methods to extend String. The link below explains extension methods and has an example of how to add a WordCount() function to String.

https://msdn.microsoft.com/en-us/library/bb383977.aspx

Mike Hixson
  • 5,071
  • 1
  • 19
  • 24