Can extend String class in .net

How to override or extend core .net classes. eg

public class String { public boolean contains(string str,boolean IgnoreCase){...} public string replace(string str,string str2,boolean IgnoreCase){...} } 

after

 string aa="this is a Sample"; if(aa.contains("sample",false)) {...} 

Is it possible?

+6
c #
source share
4 answers

The String class is sealed, so you cannot inherit it. Extension methods are your best bet. They have the same sensation as instance methods without the cost of inheritance.

 public static class Extensions { public static bool contains(this string source, bool ignoreCase) {... } } void Example { string str = "aoeeuAOEU"; if ( str.contains("a", true) ) { ... } } 

You will need to use VS 2008 to use extension methods.

+22
source share

The String class is sealed, so you cannot extend it. If you want to add functions, you can either use extension methods or wrap them in your own class and provide any additional functions that you need.

+2
source share

In general, you should try to figure out if there is another method that will suit your needs in a similar way. For your example, Contains is actually an IndexOf wrapper method, return true if the return value is greater than 0, otherwise false . As it happens, the IndexOf method has several overloads, one of which is IndexOf( string, StringComparison ): Int32 , which can be set to honor or ignore.

See String.IndexOf Method (String, StringComparison) (System) for more details, although the example is a bit strange.

See StringComparison Enumeration (System) for the various options available when using the StringComparison enumeration.

+1
source share

You can also use the adapter template to add additional features. You can overload the statement so that it feels like an inline string. Of course, this will not be automatic for existing "string" applications, but your decision to directly inherit from it, if possible.

0
source share

All Articles