xxxxxxxxxx
private static readonly MethodInfo ExtensionMethod =
typeof(ObjectExtensions).GetMethod(nameof(ObjectExtensions.NewMethod));
xxxxxxxxxx
/*
-Extension methods are methods that can be inserted into existing types without creating a new derived type, recompiling,
or otherwise modifying the original type.
-Extension methods are static methods, but in C# they are called as if they were normal C# methods.
They use this modifier in their parameters.
-C# already includes a LINQ library extension method based on the IEnumerable interface, and any class that inherits from this interface, such as an array or list.
But if you want to add a new function to any data type, you should make a static class and add any static method as an extension method.
*/
//EX We want to add a print method that can print any type of array.
//First step to create static class
public static class Extensiton {
//create your function =should be static, and this keyword must precede the method parameter.
public static void Print < T > (this T[] array) {
foreach(var item in array) {
Console.WriteLine(item);
}
}
}
//calling Fucntion
public class Program {
static void Main(string[] args) {
var numbers = new int[] {
1,
2,
3,
4,
5
};
var fruits = new [] {
"orange",
"banana",
"lemon",
"grabs"
};
//print numbers
numbers.Print(); // 1 2 3 4 5
//print fruits
fruits.Print(); // orange banana lemon grabs
//notice this keyword replace parameter as without extension method you will do this Print(fruits) or Print(numbers)
}
}