Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is StringValues assignable to String

Tags:

c#

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.

like image 706
eddyP23 Avatar asked Feb 12 '20 15:02

eddyP23


2 Answers

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.

like image 139
canton7 Avatar answered Nov 20 '22 14:11

canton7


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.

like image 38
Christopher Avatar answered Nov 20 '22 14:11

Christopher