Skip to content

[API Proposal]: Uri from interpolated string #66470

@scalablecory

Description

@scalablecory

Background and motivation

I frequently see code like this:

new Uri($"http://localhost/things/{Uri.EscapeDataString(id)}/?foo={Uri.EscapeDataString(foo)}")
new Uri(baseUri, $"/things/{Uri.EscapeDataString(id)}/?foo={Uri.EscapeDataString(foo)}")

I'd rather do something like:

Uri.Create($"/things/{id}/?foo={foo}", UriKind.Relative);
Uri.Create($"http://localhost/things/{id}/?foo={foo}", UriKind.Absolute);
Uri.Create($"{baseUri}/things/{id}/?foo={foo}");

(Note, this is integrating the "base uri" into the format string. Not sure of corner cases but it feels pretty natural)

May be able to use a format string to indicate "%20" vs "+" style escaping.

API Proposal

ref struct UriInterpolatedStringHandler
{
    // all the interpolated handler members.
}

class Uri
{
    public static Uri Create(ref UriInterpolatedStringHandler handler);
}

API Usage

string GetThingFromWebService(HttpClient client, string thingId)
{
    Uri uri = Uri.Create($"{client.BaseUri}/things/{thingId}/");

    using var req = new HttpRequestMessage { Uri = uri };
    // ...
}

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Net

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions