Extension Methods
public class MyUtils { public static bool IsNumeric(string s) { float output; return float.TryParse(s, out output); } }Now you could check a string by executing a line of code like this:
string test = "4"; if (MyUtils.IsNumeric(test)) Console.WriteLine("Yes"); else Console.WriteLine("No");However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:
public static class MyExtensionMethods { public static bool IsNumeric(this string s) { float output; return float.TryParse(s, out output); } }The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the IsNumeric() method directly on strings, like this:
string test = "4"; if (test.IsNumeric()) Console.WriteLine("Yes"); else Console.WriteLine("No");
Having problems with this chapter? Ask in our forums!
Could this article help your friends? Please help us to help them by sharing it on Facebook or Twitter: