Free Web Development Online Tutorials, Learn to Code
Learn C# Extension methods, Free C# Tutorial for Beginners, C# Development Guide

C# Extension method example

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

What is extension method in C#?

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!

extension method c# string

Here we will be creating a extension method in c#, just follow the steps below

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();
       }
    }
}

how to call extension method in c#

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#

This way you can write your own extension method for any c# data type like array, bool, decimal, datarow, file, float etc.

Comment
Name
Email
Website
Subscribe
 

.Net Extension methods
Other Online Tutorial

C# .net Interview Questions Answers