Extension Method Resolution
Understand how the compiler finds extensions.
How the Compiler Finds Extensions
When you write value.Method() and no instance method matches, the compiler looks for an extension method. But it only considers extensions whose containing namespace is in scope through a using directive.
using Directives Bring Extensions Into Scope
An extension is only visible if you import its namespace. Without the right using, the method appears not to exist even though it is compiled into the assembly.
using System;
using MyHelpers; // brings StringExtensions into scope
namespace MyHelpers
{
public static class StringExtensions
{
public static string Reverse(this string s)
{
var arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("hello".Reverse());
}
}All lessons in this course
- Defining Extension Methods
- Extending Interfaces and Generics
- Extension Method Resolution
- Designing Good Extensions