Search code examples
c#.net.net-coreuri.net-6.0

I get error when using a valid Uri constructor


Im new to C# and am struggling to understand this: I'm trying to use one of the .NET 6.0 Uri constructors, namely this one: Uri(Uri baseUri, string? relativeUri);

My code looks like this:

string baseUrl = "https://example.com";
string? route = null;
Uri test = new Uri(baseUrl, route);

But I get this error:

'route' may be null here. 
Argument 2: cannot convert from string to bool

Solution

  • Uri(Uri baseUri, string? relativeUri);

    Okay, but you did not do that. You passed (string, string?).

    If you want to call the (Uri, string?) constructor, do so:

    Uri baseUrl = new Uri("https://example.com");
    string? route = null;
    Uri test = new Uri(baseUrl, route);
    

    The error message you get is from the compiler picking the closest overload from what you have given it, which would be (string, bool). And since your second parameter is not a bool, you get this error.