URI Return String
ID |
csharp.uri_return_string |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
CSharp |
Tags |
api-design, code_smell, uri |
Description
Reports methods whose name ends with Url or Uri and whose return type is
string. The .NET design guidelines recommend exposing URLs as System.Uri
values rather than raw strings: the type captures parsing, distinguishes opaque
URI from arbitrary text, and lets the caller reject malformed input early.
Rationale
Uri is the strongly-typed contract for URLs in .NET. Returning a raw string
forces every consumer to call new Uri(…) again — duplicating the parse work
and burying the failure mode in the consumer instead of the producer. APIs that
return Uri make malformed inputs impossible by construction.
public class Catalog
{
public string GetProductUrl(int id) => // FLAW
$"https://api.example.com/products/{id}";
public Uri GetProductUri(int id) => // OK
new Uri($"https://api.example.com/products/{id}");
}
Remediation
Change the return type to System.Uri and construct the value inside the method.
If callers genuinely need a string, expose a separate property
Uri.AbsoluteUri on the returned value or keep the string method with a name
that does not end with Url/Uri.