Reputation: 3354
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.
Upvotes: 0
Views: 1515
Reputation: 1
try this
public static class Colores
{
public static Color Rojo = Color.FromArgb(0xE51600);
public static Color Azul = Color.FromArgb(0x004183);
public static Color Verde = Color.FromArgb(0x00865A);
public static Color Plata = Color.FromArgb(0xC4C5C7);
public static Color Gris = Color.FromArgb(0x58585A);
public static Color Cafe = Color.FromArgb(0x632600);
public static Color Negro = Color.Black;
}
Upvotes: -2
Reputation: 71591
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; the Color class itself, though it has static members, is not static, and so many instances of Colors can exist. 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();
Upvotes: 8
Reputation: 3461
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();
}
Upvotes: 0
Reputation: 24232
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.
Upvotes: 1
Reputation: 131806
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.
Upvotes: 4