-1

I am deriving a class from String, but it won't allow me to inherit from that class. What do I need to do if I want to inherit like this?

public class a : string
{ 
  //class definition
}
halfer
  • 19,824
  • 17
  • 99
  • 186
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • 5
    You can't, `string` is a sealed class. See [here](https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx) – Maarten Sep 30 '15 at 08:48
  • The short answer is as Maarten says... the question is must you inherit string? Will a string extension do?... I suspect a string extension method will serve your purpose https://msdn.microsoft.com/en-us/library/bb383977.aspx – Paul Zahra Sep 30 '15 at 08:49
  • what is your reasoning for wanting to derive from String? (which is not possible to do anyway as it is a sealed class) – Ahmed ilyas Sep 30 '15 at 08:49
  • No particular reason for doing like this. i was just checking – sujith karivelil Sep 30 '15 at 08:51

3 Answers3

4

You cannot inherit from String because it is sealed. If you have to extend the provided functionality, you have two options:

  • Write a wrapper class around String and implement the methods yourself.
  • Use Extension methods
germi
  • 4,628
  • 1
  • 21
  • 38
0

You cannot inherit from string class as it is sealed. For any additional behavior to the string class consider creating extension methods.

Yogi
  • 9,174
  • 2
  • 46
  • 61
0

Short answer :

You can't derive from basic type.

Long answer :

You can't because the String class is maked as sealed, preventing inheritance.

If you want to add methods to the string object, you can use extention methods (more info here : https://msdn.microsoft.com/en-us/library/bb383977.aspx)

Remy Grandin
  • 1,638
  • 1
  • 14
  • 34