How it works
A URI contains structural characters with special meanings. An ampersand can separate query parameters, and a hash can begin a fragment. When those characters are part of user data rather than URI syntax, encode the component before inserting it into the surrounding structure. EscapeDataString performs that component-level representation step.
The sample's query contains a hash, spaces, and an ampersand. Its escaped form can be placed after q= without turning the ampersand into another parameter or the hash into a fragment boundary. UnescapeDataString reconstructs the original query for this round-trip demonstration; no network request is made.
Escaping is not validation, sanitization for every context, or encryption. A correctly escaped string can still represent an invalid search query or sensitive content. The URL's scheme and host also need their own policy when external links are accepted. Encoding one component does not establish that the complete destination is appropriate.
Avoid repeatedly escaping data that is already encoded. A percent sign introduced by the first encoding can itself be encoded later, changing what a receiver sees. Keep track of whether a value is raw data or an encoded component, and perform the transformation at a clear construction boundary.
Practice with a plus sign, a percent sign, a non-ASCII name, and an empty query. Compare the encoded component with the assembled URI. Then add a second parameter using a separate encoded value, leaving the structural ampersand between parameters unescaped.
Finally, compare escaping a query value with escaping an entire URI string. They solve different problems because structural separators must retain their roles. Prefer a structured URI or query-building API when constructing more complicated addresses, and test the decoded parameter values rather than judging correctness only by whether the output looks like a plausible link.
A working example
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
string query = "C# & .NET";
string escaped = Uri.EscapeDataString(query);
Console.WriteLine(escaped);
Console.WriteLine(Uri.UnescapeDataString(escaped) == query);
Console.WriteLine("https://example.invalid/search?q=" + escaped);
Expected output
C%23%20%26%20.NET True https://example.invalid/search?q=C%23%20%26%20.NET
Escape the query value, not the already assembled URI structure.