-
Notifications
You must be signed in to change notification settings - Fork 1
Extension Methods
Mario Gutierrez edited this page Jan 7, 2017
·
1 revision
- Extension methods must be defined in a static class, and must be static.
- These add methods to existing types.
- The target type is specified as the first parameter.
- Additional parameters are allowed.
using System.Reflection;
static class MyExtensions
{
// Targeting the Rectangle type.
public static bool IsSquare(this Rectangle r)
{
return r.Height == r.Width;
}
// Targeting the int type.
public static int Add(this int a, int b)
{
return a + b;
}
// You can also define extension methods targeting interfaces.
public static void PrintAll(this System.Collections.IEnumerable iterator)
{
foreach (var item in iterator)
{
Console.WriteLine(item);
}
}
}
int myInt = 30;
int result = myInt.Add(2); // Using an extension method from MyExtensions.
- Abstract Classes
- Access Modifiers
- Anonymous Methods
- Anonymous Types
- Arrays
- Attributes
- Console I/O
- Constructors
- Const Fields
- Delegates
- Enums
- Exceptions
- Extension Methods
- File IO
- Generics
- Interfaces
- Iterators
- LINQ
- Main
- Null Operators
- Parameters
- Polymorphism
- Virtual Functions
- Reflection
- Serialization
- Strings
- Value Types
- "Base" Keyword
- "Is" and "As"
- "Sealed" Keyword
- nameof expression