Why is StringValues assignable to String

There's a user-defined implicit conversion to string:

Source

public static implicit operator string (StringValues values)
{
    return values.GetStringValue();
}

See User-defined conversion operators.

The MSDN Docs aren't very clear, but they're there if you know where to look.


While it is true that the types StringValues and String are not in any way related on the class diagrams (strings being marked sealed, StringValues being a struct), that only means Polymorphy can not affect them there.

There are rare cases where there are implicit, prewritten converters between two types. Those are admittedly a relatively rare sight, so it is understandable if you do not expect one.

Practice taught us that overely agressive implicit conversions causes issues. .NET and C# are intentionally strongly typed. So accordingly, they are very conservative with implicit conversions. Which result in people not expecting them, much like the Spanish inquisition.

While strong typification has it's own downsides, personally, I prefer it. See the PHP and JavaScript examples of this comic for weak typisation in action. Hint: JavaScript does the wrong thing in both cases. One just happens to have the right result.

Tags:

C#