I have a class:
namespace MyNamespace
{
public abstract class Class1
{
public static string X()
{
return "Greetings from a method.";
}
}
}
and an extension method:
namespace MyNamespace
{
public static class Class1Extension
{
public static string Y(this Class1 c1)
{
return "Greetings from extension method.";
}
}
}
And when I try to access the extension method, the compiler gives me this error:
'MyNamespace.Class1' does not contain a definition for 'Y'
Here's how I use it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using MyNamespace;
namespace Test_Console
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Class1.X());
Console.WriteLine(Class1.Y());
Console.ReadLine();
}
}
}
You are trying to call the extension method like this:
Class1.Y();
That doesn't work. Extension methods always operate on an instance, not on a class itself:
var c = new Class1Impl(); // derived from Class1
c.Y();
In other words:
Extension methods are a way to add instance methods to class hierarchies without actually changing the existing classes.
You can't use them to add static methods to a class. In fact, there is no mechanism in C# that would allow adding static methods to a class other than the traditional way of simply adding them directly to the class.
Extension methods are really just syntactic sugar.
The compiler changes the above code to the following:
Class1Extension.Y(c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With