Blaze Phoenix
Blaze Phoenix

Reputation: 889

Is is possible to extend constructors in c#?

I am wondering if there is an existing class (such as UIColor from Monotouch) if there is a way to extend a constructor. That would make working with the library we have easier.

public static class UIColorExtender
{
    public UIColor(string hex)
    {
        this = ConvertHexToUIColor(hex); // This isn't necessarily the code, just filler.
    }
}

Upvotes: 0

Views: 7042

Answers (3)

Jimmy B. Carlsen
Jimmy B. Carlsen

Reputation: 26

Maybe this question is trying to achieve the same as you? UIColor from Hex in Monotouch

When looking at the UIColor class, it seems that it mostly uses a factory pattern when using other formats than just 4 float values for R, G, B and alpha:

UIColor.FromHSB(float, float, float)
UIColor.FromWhiteAlpha(float, float)

..and many more

So I think the best solution would be like Luis' in the question above.

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48154

Constructors can't be extended. You can inherit from the class and implement your own or, if the class in question isn't full of read-only properties, create an initialization method to call after the constructor.

Upvotes: 0

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

No, there is no such way presently in C#. Inherit from the class and use your own constructor logic. Use the new class in place of the old one.

Upvotes: 4

Related Questions