It looks for static classes inside the namespaces you declared at the top of your file, like 'using System.Linq;' (if it cannot find anything in the current namespace) Then it simply replaces the call with
MyExtendedMethods.square
Pregunta
I believe I understand the concept of extension methods, except one detail. It seems you can create a random (static) class with a random static
method using this
on a parameter. I believe this parameter has to match the type of class you want to extend (or one it's inheriting from).
An example:
public static class MyExtendedMethods
{
public static int square(this int num)
{
int result = 0;
result = num * num;
return result;
}
}
class Program
{
static void Main(string[] args)
{
int myNum = 3;
myNum = myNum.square();
Console.WriteLine(myNum);
}
}
How does .NET know where to find this class and method (MyExtendedMethods.square()
)? I don't see the classes related in any way. Is it looking through all classes in the project for a possible extension?
Solución
It looks for static classes inside the namespaces you declared at the top of your file, like 'using System.Linq;' (if it cannot find anything in the current namespace) Then it simply replaces the call with
MyExtendedMethods.square