Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Extension methods examples in C# .Net

How to Implement Extension method in .Net C#

In this article you will learn about how to work with Extension methods in C# .Net

What is extension method?
Extension methods are basically additional methods, in .net that allow you to add a new method to existing types without modifying, deriving or recompiling the original class, struct or interface.

For example in .Net we have string data type, in string there many existing methods like split(), substring() etc, now you want to add a new method to string type, give any name, let’s call that FormattedString() , now without modifying the string type in .net library we can add this new method FormattedString() by creating an additional class.
Let���s look at the code example how to do that!

Step 1: Create a class library , then create static class like we have created "StringExtensions"
Step 2: Create a static method give whatever meaningful name you want, like we have created "FormattedString"
notice, how the first parameter "this string s", this means object itself
namespace WTRConsoleApplication
{
   public static class StringExtensions
    {
       public static string FormattedString(this string s, string input)
       {
           // do whatever you want for formatting
           StringBuilder objStr = new StringBuilder();
           objStr.Append(input);
           objStr.Append("WTR Signed");

           return objStr.ToString();
       }
    }
}


Now let's understand how this new method will work
class Program
{
static void Main(string[] args)
{
string s="Hello";
string result = s.FormattedString(" Student! ");
Console.WriteLine(result);
//result: Hello Student! WTR Signed
                }
    }

We are using the extention method like anyother string method, see how the method working.
extension method c# .net

Note: in this extension method example we have just appended the input value and returned string, kept it simple just to make you understand.
You can write whatever logic you need.
Hope you understood how to create and use extension method in C#



 
.Net Extension methods
Learn C# Online Tutorial


Group Training