0

Possible Duplicate:
Does C# have extension properties?

I have the following:

 public static class EnumExt
    {
        public static string D2(this Enum key)
        {
            return Convert.ToInt32(key).ToString("D2");
        }
    }

Which I use like this:

PageType.ContentBlock.D2()

Where PageType is an Enum.

Is there a way I can do this so that D2 is a property and rather not a method? It doesn't seem to make much sense to me that I always have to put the () after D2 ?

Community
  • 1
  • 1
  • 1
    I have looked for the answer to this and I found the answer to be no. I hope I'm wrong and there is a way. – Johan Larsson Oct 29 '12 at 08:51
  • No - you cannot. C# at this point in time will not support what you are asking for. – Ramesh Oct 29 '12 at 08:53
  • So you are asking this just because you cant be bothered to add the brackets? How you ever considered using VB.Net, you can save yourself quite a few characters with that! (facepalm) – musefan Oct 29 '12 at 08:56

2 Answers2

1

No, that's why it is called Extension Method. While it may look like it could be converted to a property if no other parameters are expected (as in var x = y.ExtensionMethod();), an extension method can take additional parameters. Example:

int y = x.Add(3);

public static int Add(this int source, int value)
{
    return source + value;
}

Also, extension methods are just "syntactic sugar". The compiler translates them into a normal method call with the source object being passed as parameter.

Example (extension methods are in a class ExtensionMethods):

int y = x.Add(3);

will be converted to

int y = ExtensionMethods.Add(x, 3);

by the compiler.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0

Well, you've got a parameter : this Enum key

even if usage "looks like" a property, remind that

PageType.ContentBlock.D2();

is equivalent to

EnumExt.D2(PageType.ContentBlock);

so, when you need a parameter, use... a method !

Does C# have extension properties?

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122