C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: This file should store a static class with public static extension methods.
Public, privateThen: In the rest of your source code, you can invoke these extension methods in the same way as instance methods.
Static: An extension method must be static and can be public so you can use it anywhere in your source code.
StaticImportant: You must specify the this-keyword before the appropriate parameter you want the method to be called upon.
C# program that uses extension method on string
using System;
public static class ExtensionMethods
{
public static string UppercaseFirstLetter(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()
{
// Use the string extension method on this value.
string value = "dot net Codex";
value = value.UppercaseFirstLetter();
Console.WriteLine(value);
}
}
Output
Dot net Codex
C# program that uses extension method, 2 parameters
using System;
static class Extensions
{
public static int MultiplyBy(this int value, int mulitiplier)
{
// Uses a second parameter after the instance parameter.
return value * mulitiplier;
}
}
class Program
{
static void Main()
{
// Ten times 2 is 20.
// Twenty times 2 is 40.
int result = 10.MultiplyBy(2).MultiplyBy(2);
Console.WriteLine(result);
}
}
Output
40
Important: If you want the method to receive other parameters, you can include those at the end.
Tip: On most of the extension methods, you need to add the "using System.Linq" directive to the top of the code.
LINQSo: Extension methods affect the high-level representation of the code, not the low-level implementation.