I don't understand why the following compiles:
StringValues sv = httpContext.Request.Query["param"];
string s = sv;
My knowledge says that a
is assignable to b
only if a
is of type b
or a
extends/implements b
. But looking at the docs it doesn't look like StringValues
extends string
(string
is a sealed class, therefore it shouldn't be even possible).
So I assume this is some implicit conversion going on here, but I can't find any info on it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With