ebattulga
ebattulga

Reputation: 10981

Possible to extend the String class in .net

How to override or extend .net main classes. for example

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?

Upvotes: 6

Views: 5582

Answers (4)

Schmuli
Schmuli

Reputation: 743

In general, you should try to see if there is another method that will answer your needs in a similar manner. For your example, Contains is actually a wrapper method to IndexOf, return true if the returned value is greater than 0, otherwise false. As it happens, the IndexOf method has a number of overloads, one of which is IndexOf( string, StringComparison ): Int32, which can be specified to honor or ignore case.

See String.IndexOf Method (String, StringComparison) (System) for more information, although the example is a little weird.

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

Upvotes: 1

Christopher Elliott
Christopher Elliott

Reputation: 87

You can also use an adapter pattern to add additional functionality. You can do operator overloading to make it feel like the built in string. Of course this won't be automatic for existing uses of "string" but neither would your solution of directly inheriting from it, if it were possible.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754575

The String class is sealed so you can't inherit from it. Extension methods are your best bet. They have the same feel 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 be using VS 2008 in order to use extension methods.

Upvotes: 22

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The String class is sealed, so you cannot extend it. If you want to add features you can either use extension methods or wrap it in a class of your own and provide whatever additional features you need.

Upvotes: 2

Related Questions