How to write extension methods in C#?
How to write extension methods in C#?
In this post am going to explain you about how write the extension method in C#?
Here am giving simple example for writing extension method for a string to capitalize the first character of the string.
see Example bellow
let us take a string
string str="sample:;
i want to convert the str value to "Sample" by extension method
like str.ToCapitalize(); which returns the "Sample" as out put
see the bellow implementation
in order to do this we required a static class
public static class StringExtensions
{
public static string ToCapitalize(this string str)
{
if (string.IsNullOrWhiteSpace(str))
{
return str;
}
if (str.Length == 1)
{
return str.ToUpper();
}
else
{
return str.Substring(0, 1).ToUpper() + str.Substring(1, str.Length - 1).ToLower();
}
}
}
as per above implementation we will get extension for string as ToCapitalize,where ever we have string variable we will get ToCapitalize(); like ToString() ;
Hope this will helps you.
Labels:
C#