0

I'm attempting to extend my custom classes and running into a problem where it cannot find the extension method.. I have and can extend any built in classes or even ones contained within DLL's. I don't know if this is a compilation error or if I'm doing something wrong. Threw together a small program for an example, won't compile..

Here's the extension:

namespace ExtensionMethodTesting.Extension
{
    public static class Extension
    {
        public static void DoSomething(this ExtensionMethodTesting.Blah.CustomClass r)
        {

        }
    }
}

Here's the Custom Class:

namespace ExtensionMethodTesting.Blah
{
    public class CustomClass
    {
        public static void DoNothing()
        {

        }
    }
}

Here's the code calling it:

using ExtensionMethodTesting.Blah;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExtensionMethodTesting.Extension;

namespace ExtensionMethodTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomClass.DoNothing();
            CustomClass.DoSomething();
        }
    }
}

I must be missing something... Anyways the exact error just for clarification is:

Error 1 'ExtensionMethodTesting.Blah.CustomClass' does not contain a definition for 'DoSomething' c:\users\damon\documents\visual studio 2013\Projects\ExtensionMethodTesting\ExtensionMethodTesting\Program.cs 16 25 ExtensionMethodTesting

Dmitry
  • 13,797
  • 6
  • 32
  • 48
Damon Earl
  • 324
  • 2
  • 8
  • 2
    just curious... why are you writing extension methods on classes that you control? Is there a reason you can't just add the methods where they belong? (I ask because you generally *don't* want to do what you're doing...) – Michael Edenfield Aug 19 '14 at 23:23
  • Mostly due to multiple developer issues. Most of it will be accomplished with inheritance instead, but there are some one off things that I'll need to extend. – Damon Earl Aug 20 '14 at 15:49
  • @MichaelEdenfield What is your bases for saying: *"you generally don't want to do what you're doing..."* – Yusha Jun 29 '18 at 17:54
  • there are some limits and edge cases with extension methods (especially related to overloads) that are not always intuitive. They exist for the purpose of extending classes in ways you _can't_ otherwise do. – Michael Edenfield Jun 30 '18 at 00:11

2 Answers2

3

Extension methods require an instance of an object. You'll have to new up a CustomClass to use it.

var custom = new CustomClass();
custom.DoSomething();

See this answer as to why that is.

Community
  • 1
  • 1
Chris
  • 4,393
  • 1
  • 27
  • 33
2

You need to instantiate an object of the CustomClass to use its extension method.

CustomClass obj = new CustomClass();
obj.DoSomething();
Mephy
  • 2,978
  • 3
  • 25
  • 31