views:

64

answers:

2

Hi all. 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.

+2  A: 

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.

Steven Sudit
+5  A: 

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());
    }
}
Jon Skeet
"Note that it is defined inside a non-nested, non-generic static class"
Steven Sudit
@Steven: What are you quoting?
Jon Skeet
return (double)(int)code; can be return (int)code, the cast is implicit.
Yuriy Faktorovich
The link from my answer: http://msdn.microsoft.com/en-us/library/bb383977.aspx
Steven Sudit
@Steven: Ah... that wasn't at all obvious without having already followed the link...
Jon Skeet
@Yuriy: I know, but in this case I think it actually increases the readability a bit - it reminds the reader of the extra conversion.
Jon Skeet
Sorry, my fault. Anyhow, +1 for showing a working example instead of just throwing the book at them. You're a kind-hearted AI.
Steven Sudit
@Jon fair enough.
Yuriy Faktorovich