In this article, we will learn about Extension Method in C# and how to create Extension Method in C#.
Extension methods are a new feature in C# 3.0. An Extension method allows you to add your own methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a static method to the existing static class. We call an extension method in the same general way; there is no difference in calling.
They themselves should be static
and should contain at least one parameter, the first preceded by the this
keyword.
static
this
keyword as the first parameter with a type in .Net and this method will be called by a given type instance on the client side.We create an extension method for a string
type, so string
will be specified as a parameter for this extension method and that method will be called by a string
instance using the dot operator.
public static class stringExtentionMethod
{
public static string CapitaliseWord(this string value)
{
// Uppercase the first letter in the string.
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
In the above example, we create method CapitaliseWord(), we are passing a string
type with this so it will be called by the string
type variable, in other words a string
instance.
In the above example, we create a method for converting the first letter of the given string
into uppercase and the rest of character in a given string
is remains the same.
Here is the complete program for creating and using the extension method.
using System;
namespace ExtensionMethod
{
public static class stringExtentionMethod
{
public static string CapitaliseWord(this string value)
{
// Uppercase the first letter in the string.
if (value.Length > 0)
{
char[] array = value.ToCharArray();
array[0] = char.ToUpper(array[0]);
return new string(array);
}
return value;
}
}
class Program
{
static void Main(string[] args)
{
string str = "tutorials rack";
//Using this Extention Method for convert the first letter of the string into uppercase.
string Capitalise_Str = str.CapitaliseWord();
Console.WriteLine("Result: {0}", Capitalise_Str);
Console.ReadLine();
}
}
}
Result: Tutorials rack
You can add extension methods to any type, even a value type. The original representation of the type does not change. Extension methods affect syntax, not execution.
I hope this article will help you to understand Extension Methods in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments