C# Extension Methods Tutorial with Examples
Today, We want to share with you C# Extension Methods Tutorial with Examples.
In this post we will show you Extension method in c#, hear for C# Extension Methods we will give you demo and example for implement.In this post, we will learn about C Sharp Extension method with an example.
Extension method in c#
In this post,we will learn about Extension method in c# an example.
Now in this post, I will explain about Extension method in c# with appropriate example.
Extension methods make it possible to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special type of static method, but they are called as if they were instance methods on the extended type.
An extension method is a static method of a static class, where the “this” modifier is supplied to the first parameter. The type of the first parameter will be the type which is extended.
Now create Console Application in Visual Studio and write below lines of code in it.
[php]public class Class1 {
public string Count() {
return (“I m in Count”);
}
public string PrintCount() {
return (“I m in PrintCount”);
}
}[/php]
Now it is required to extend the definition of this class so create a static class to create an extinction method like:
[php]public static class AAA {
public static void NewMethod(this Class1 ob) {
Console.WriteLine(“Hello I m extended method”);
}
}
[/php]
In the above code I just create a method that name is NewMethod with a parameter using this to define which type of data I need to be extend, now let’s see how to use this function.
[php]
class Program {
static void Main(string[] args) {
Class1 ob = new Class1();
ob.Count();
ob.PrintCount();
ob.NewMethod();
Console.ReadKey();
}
}
[/php]
Read :
Summary
You can also read about AngularJS, ASP.NET, VueJs, PHP.
I hope you get an idea about c# extension methods tutorial.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.