Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolated String Handlers: Implicit conversions to strings #5077

Closed
333fred opened this issue Aug 17, 2021 · 1 comment
Closed

Interpolated String Handlers: Implicit conversions to strings #5077

333fred opened this issue Aug 17, 2021 · 1 comment

Comments

@333fred
Copy link
Member

333fred commented Aug 17, 2021

In a previous LDM, we rejected defining a conversion from string to a custom handler type, saying that API authors should define one themselves if they so choose. However, this can cause some interesting issues with best common type that can require a language designer to explain why things work the way they do:

// No implicit conversion defined
using System;
var x = ((bool)(object)false) switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; // Error: no best common type
Console.WriteLine(x);
// Implicit conversion from CustomHandler to string
using System;
var x = ((bool)(object)false) switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; // x is string
Console.WriteLine(x);

public partial struct CustomHandler
{
    public static implicit operator string(CustomHandler c) => c.ToString();
}
// Implicit conversion from string to CustomHandler
using System;
var x = ((bool)(object)false) switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; // x is CustomHandler
Console.WriteLine(x);

public partial struct CustomHandler
{
    public static implicit operator CustomHandler(string c) => ...;
}

This type of friction can arise in a number of places, such as lambda type inference, ternary best type inference, or null-coalescing best type inference.

While I don't think we should define a language-level conversion here, I think we should make a recommendation (as a language) that interpolated string handler types define a conversion from string to themselves in order to help users with these scenarios.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant