Why does CSharpExtensions.ClassifyConversion return an explicit reference conversion for object / string?

Viewed 40

The CSharpExtensions.ClassifyConversion(Compilation, ITypeSymbol, ITypeSymbol) method returns an explicit reference conversion if called with the special type object as source and the special type string as destination argument:

var objectTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_Object);
var stringTypeSymbol = context.Compilation.GetSpecialType(SpecialType.System_String);
var conversion = context.Compilation.ClassifyConversion(objectTypeSymbol, stringTypeSymbol);

As far as I know C# doesn't specify a built in object to string conversion: C# language reference. Why does it return an explicit reference conversion and what does it imply? How would the c# syntax of such a conversion look like? If ClassifyConversion is called with an empty user defined class as source argument and the string special type as destination argument, NoConversion is returned as expected.

1 Answers

What you're seeing is just a bog-standard cast of object to string, IE:

public string M(object o)
    => (string)o;

IE: At runtime, check if o is an instance of string. If it is, return it as string. If it isn't, throw InvalidCastException.

Specifically you're seeing this case from §10.3.5 Explicit reference conversions:

  • From object and dynamic to any other reference_type.

You don't see the conversion with your user-defined class because it's more specific than object (and as such is known to never have a reference conversion to string.)

Related