views:

82

answers:

2

Hi,

the source is throwing the error:

'nn.asdf' does not contain a definition for 'extension_testmethod'

and i really don't unterstand why...

using System.Linq;
using System.Text;
using System;

namespace nn
{
    public class asdf
    {
        public void testmethod()
        {
        }
    }
}
namespace nn_extension
{
    using nn;
    //Extension methods must be defined in a static class
    public static class asdf_extension
    {
        // This is the extension method.
        public static void extension_testmethod(this asdf str)
        {
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace.
    using nn;
    using nn_extension;
    class Program
    {
        static void Main(string[] args)
        {
            asdf.extension_testmethod();
        }
    }
}

any ideas?

+6  A: 

An extension method is a static method that behaves like an instance method for the type being extended, that is, you can call it on an instance of an object of type asdf. You can't call it as if it were a static method of the extended type.

Change your Main to:

asdf a = new asdf();
a.extension_testmethod();

Of course, you can always call like a simple, static, non-extension method of the declaring type (asdf_extension):

asdf_extension.extension_testmethod(null);
Mehrdad Afshari
+1  A: 

Extension methods apply to class instances:

var instance = new asdf();
instance.extension_testmethod();
Darin Dimitrov