Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add extension method to an abstract class in C#

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();
            }
        }
    }
like image 653
dpp Avatar asked Jan 18 '26 10:01

dpp


1 Answers

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);
like image 145
Daniel Hilgarth Avatar answered Jan 21 '26 00:01

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!