1

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?

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

Comments

1

Extension methods apply to class instances:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.