Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to extend the String class in .net

Tags:

c#

.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?

like image 315
ebattulga Avatar asked Feb 08 '09 14:02

ebattulga


People also ask

Can we extend String class?

Since String is final there is no way anyone can extend String or override any of String functionality. Now if you are puzzled why String is immutable or final in Java.

Can we define extension method for static class?

No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the ConfigurationManager interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.


1 Answers

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.

like image 164
JaredPar Avatar answered Nov 09 '22 00:11

JaredPar