Search code examples
c#privateimplicit-conversion

Alternative to private implicit conversion operators


I'm trying to write a simple string enum. Obviously I'd normally use a standard enum but I need spaces in the strings.

I've tried to prevent construction of any other instances by making the constructor private. However, I also wanted an implicit conversion to make the static declarations easier/neater (last line)

public class StringEnum
{
    public static StringEnum Foo      = "A Foo";
    public static StringEnum Bar      = "A Bar";
    public static StringEnum Wibble   = "A Wibble";
    public static StringEnum Crotchet = "A Crotchet";
    //etc...

    //implicit cast to string
    public static implicit operator string(StringEnum s) { return s.privateString; }

    //private construction
    private string privateString;      
    private StringEnum(string s) { this.privateString = s; }
    private static implicit operator StringEnum(string s) { return new StringEnum(s); }
}  

This implicit operator fails to compile with "The modifier private is not valid for this item". I could make it public but then other code can construct non enum members. I could also just get rid and new up the static instances, but it looks a lot neater as above.

Just wondered why you can't have private conversion operators really, and whether someone can suggest an alternative way that satisfies my pedantry?


Solution

  • Just wondered why you can't have private conversion operators

    Operators are just syntactic sugar around special methods. In the case of an implicit conversion, the operator gets compiled to something like:

    public static string op_Implicit(StringEnum s)
    {
        // implementation
    }
    

    private methods are meant to hide implementation details - operators are meant to make code outside of the class look cleaner. Privately it would be very straightforward just to create a method to do the conversion rather than an implicit operator. So there's very little value in having a private operator since it only affects the private interface - it doesn't affect the public interface at all. So the benefit of such a feature does not justify the costs (design, implementation, testing, testing, and more testing, documentation, and maintenance)

    and whether someone can suggest an alternative way that satisfies my pedantry?

    Just make the "conversion" a private method instead of an operator.