Adam S
Adam S

Reputation: 9255

Extension methods to extend class members?

I'd like to write an extension method that extends some member of my class. Specifically, I'd like to extend an enum. However, this is not working:

namespace mynamespace
{
    public class myclass
    {
        public enum ErrorCodes
        {
            Error1, Error2, Error3
        }

        public static double GetDouble(this ErrorCodes ErrorCode)
        {
            return (double)((int)ErrorCode);
        }

        public void myfunc()
        {
            ErrorCodes mycode;
            MessageBox.Show(mycode.GetDouble().ToString());
        }
    }
}

Specifically, it doesn't recognize GetDouble() as an extension. This is not just for enums either, I tried creating an extension method for doubles and had the same problem, too.

Upvotes: 1

Views: 1964

Answers (2)

Steven Sudit
Steven Sudit

Reputation: 19640

The extension method must be defined in a static class.

See the manual.

edit

As Jon pointed out, the static class must be top-level, not nested.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504082

You can only write extension methods in top-level, static, non-generic classes, but they can extend nested classes. Here's a complete example, based on your code:

using System;

public static class Extensions
{
    public static double GetDouble(this Outer.ErrorCode code)
    {
        return (double)(int)code;
    }
}

public class Outer
{
    public enum ErrorCode
    {
        Error1, Error2, Error3
    }
}

public class Test
{
    public static void Main()
    {
        Outer.ErrorCode code = Outer.ErrorCode.Error1;
        Console.WriteLine(code.GetDouble());
    }
}

Upvotes: 5

Related Questions