c# - Alternative to private implicit conversion operators -
i'm trying write simple string enum. i'd use standard enum need spaces in strings.
i've tried prevent construction of other instances making constructor private. however, wanted implicit conversion make 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 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 compile "the modifier private not valid item". make public other code can construct non enum members. rid , new static instances, looks lot neater above.
just wondered why can't have private conversion operators really, , whether can suggest alternative way satisfies pedantry?
just wondered why can't have private conversion operators
operators syntactic sugar around special methods. in case of implicit conversion, operator gets compiled like:
public static string op_implicit(stringenum s) { // implementation }
private
methods meant hide implementation details - operators meant make code outside of class cleaner. privately straightforward create method conversion rather implicit operator. there's little value in having private operator since affects private interface - doesn't affect public interface @ all. benefit of such feature not justify costs (design, implementation, testing, testing, , more testing, documentation, , maintenance)
and whether can suggest alternative way satisfies pedantry?
just make "conversion" private method instead of operator.
Comments
Post a Comment