tags:

views:

531

answers:

4

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?

+2  A: 

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.

Brian Rasmussen
+18  A: 

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.

JaredPar
@JaredPar: One correction, you don't need VS 2008 to use extension methods. You need the C# compiler for C# 3.0 which is in .NET 3.5. VS 2008 is just the IDE and not what provides the functionality.
casperOne
@casperOne, correct. I usually say VS 2008 because it's more commonly known. What's even more fun, is you can compile 2.0 applications with extension methods if you provide your own Extension attribute. http://blogs.msdn.com/jaredpar/archive/2007/11/16/extension-methods-without-3-5-framework.aspx
JaredPar
@casperOne - to turn that back at you, "or mono 2.0" ;-p
Marc Gravell
A: 

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.

Christopher
+1  A: 

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.

Schmuli
it was Good idea
ebattulga