using extension methods C#

Extension. An extension method has simplified calling syntax. It represents a static method as an instance method. Extension methods can lead to simpler syntax.
The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class, like this:

Now you could check a string by executing a line of pre like this: string test = “4”;

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:

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”;


Example 2

public static bool ToBoolean(this int source){
//do it
//return it

Example 3:

using extension methods C#
4.7 (93.33%) 3 votes