Thursday, February 10, 2011

How can i add a method to mscorelib

Hi. I want to add some methods to mscorlib. For example:

string abc;

abc.IsNumeric()

i hope could explain my question.

  • You can't add methods to mscorlib, however you can use extension methods so they appear as if they are defined on string, e.g.

    public static class StringExtensions
    {
        public static bool IsNumeric(this string s)
        {
            // TODO
        }
    }
    

    Which you can then call as you requested, e.g.

    "1234".IsNumeric()
    
    From Greg Beech
  • You got a good answer by Greg. Just wanted to add that you can read more about extension methods here:

0 comments:

Post a Comment