1

I try to add a method to the color class in C#

public static class ColorExtensions 
{
    public static System.Drawing.Color GrayTone(int Darkness)
    {
        return Color.FromArgb(255 - Darkness, 255 - Darkness, 255 - Darkness);
    }
}

But I cannot use it like

Color MyColor = Color.GrayTone(80);

Using

public static class ColorExtensions 
{
    public static Color MakeBlack(this Color color)
    {
        return Color.Black;
    }
}
Color Test = Color.Beige.MakeBlack();

works. How can I add the method GrayTone to the color class? I read Can I add extension methods to an existing static class? but unfortunately I cannot translate it into my Situation.

Community
  • 1
  • 1
  • Have you read the *accepted* answer? (`No. Extension methods require an instance of an object.`) like `Color.Beige` – I4V May 27 '13 at 17:07

1 Answers1

1

This isn't an extension method, so you need to specify the type name:

Color MyColor = ColorExtensions.GrayTone(80);

In order to make an extension method, you would need to provide an instance of Color, which requires an instance, not just the class name. There is no way to add a static method to an existing class.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373