user8417115
user8417115

Reputation:

How can I add static Extention method to a existing class in C#

for example, I can to use Color (the building class like that)

Color c = Color.GreenSmile();

this is my extension method, But I don't want to use an Instance. It is possible?

   public static Color GreenSmile(this Color color)
        {
           return Color.FromArgb(83, 255, 26);
        }

Upvotes: 2

Views: 103

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460018

No, you can't omit the Color instance because an extension method needs an instance of the type it extends as first argument and the this keyword.

I want a static method, to use the name of the class.

You could create a new class Color in it's own namespace, although that could cause confusion.

namespace Drawing.Utilities
{
    internal class Color
    {
        public static System.Drawing.Color GreenSmile()
        {
            return System.Drawing.Color.FromArgb(83, 255, 26);
        }
    }
}

Now you can use this method as it was a System.Drawing.Color method:

var greenSmile = Color.GreenSmile(); // add using Drawing.Utilities;

But as mentioned above this can cause confusion, espcially because the method returns a different Color-type than itself. So it 's certainly better to use a different name for this class(ColorUtility).

Upvotes: 3

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

An extension-method is nothing but a static method that expects an instance of your class. However in your case you don´t seem to use the provided instance at all, so you can simply omit it from the method-signature and turn it into a normal static method:

public static Color GreenSmile()
{
    return Color.FromArgb(83, 255, 26);
}

Now you can call it like this:

Color c = MyClass.GreenSmile();

Upvotes: 0

Related Questions