views:

85

answers:

4

Hi
I was trying to write a simple extension method for Color static class which return Black and White equivalent of that color.
The problem is that extention methods can't return Static types...
So, how can I do this?! please help me.

+4  A: 

If you're referring to System.Drawing.Color - it's not a static class ... it's a struct. You should be able to return an instance of it from a method. It just so happens that the Color structure includes static members to represent specific colors - like: Color.Black and Color.White.

If you're not referring to that type, then please post a short sample of the code that fails.

LBushkin
just to be clear, Color can also be used with arbitrary ARGB values.
Nathan
+6  A: 

The problem is that NO method can return a static type. Static classes are stateless (or have only static state), and thus have only one "instance" that is globally accessible from any code referencing the namespace.

You can return a Color; it's not static. You can also apply an extension method to a Color. If you do this, then you can call an extension method on one of the static members of the non-static Color struct:

public static class MyColorsExtensions
{

   public static Color ToGreyScale(this Color theColor) { ... }

}

...

var greyFromBlue = Color.Blue.ToGreyScale();
KeithS
A: 

It's hard to understand what you are trying to say, but if you are trying to create a extension method for a static class, that is impossible because extension methods are for class instances.

Zach Johnson
A: 

Is this what you're looking for? This is an extension method returning a static color struct.

public static class ColorExtensions
{
    private static Color MYCOLOR = Color.Black;
    public static Color BlackAndWhiteEquivalent(this Color obj)
    {
        // stubbed in - replace with logic for find actual
        // equivalent color given what obj is
        return MYCOLOR;
    }
}

and the test

    [Test]
    public void FindBlackAndWhiteColorEquivalent()
    {
        Color equivalentColor = Color.Black.BlackAndWhiteEquivalent();
    }
Dave White