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.
views:
85answers:
4If 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.
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();
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.
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();
}