views:

118

answers:

2

Any ideas? I marked it as static but it's not working!

class ExtensionMethods
{
    public static int Add(this int number, int increment)
    {
        return number + increment;
    } 
}
+19  A: 

You are missing a static on the class. The compiler should have told you this?

public static class ExtensionMethods
Nat Ryall
this is the solution, but the compiler wont tell you this. as far as it is concerned, the syntax is valid. it has no idea that you are trying to make an extension method.
Muad'Dib
It can and does - http://msdn.microsoft.com/en-us/library/bb397656.aspx
ICR
+11  A: 

I think, it needs to be defined in a static class:

namespace MyNameSpace
{
    public static class ExtensionMethods
    {
        public static int Add(this int number, int increment)
        {
            return number + increment;
        } 
    }
}

You must also include a using MyNameSpace; in the code file you want to use them in, unless it is in the same namespace

JDunkerley
Spot on. Extension methods can only be defined on static classes.
Programming Hero