Working with strings in C#: the practical guide (create, compare, format, split, convert)
Almost every page of an ASP.NET application handles text: query strings, form fields, connection strings, file names, HTML fragments, CSV exports. C# gives you one type for all of it, string, and a large toolbox around it. This guide is the map of that toolbox: what a string really is, how to write one, and the handful of rules that prevent most string bugs in production code. Each section links to a more detailed article on this site or to Microsoft's reference documentation.
What a C# string is
A C# string is an alias for System.String: the two names compile to exactly the same type, which is why the choice between them is a matter of style (see string vs String). Microsoft's strings programming guide describes a string as a sequential, read-only collection of Char objects, each one a UTF-16 code unit.
Two consequences matter every day:
- Strings are immutable. Methods such as
Replace,ToUpperorTrimnever change the original; they return a new string. Code likename.Trim();on its own line does nothing useful: you must writename = name.Trim();. - Length counts code units, not visible characters. An emoji or some accented letters written in decomposed form take more than one
char, soLengthandSubstringcan split them. For user-facing truncation, test with real data.
Writing string literals
C# offers three kinds of literal, and choosing the right one removes most escaping headaches:
string path = "C:\\inetpub\\wwwroot\\app"; // regular: escape backslashes
string path2 = @"C:\inetpub\wwwroot\app"; // verbatim: backslashes kept as typed
string json = """
{ "name": "Postback Notes", "tags": ["asp.net", "c#"] }
"""; // raw string literal: quotes kept as typed
Verbatim strings (prefix @) suit Windows paths and multi-line SQL. Raw string literals, delimited by at least three double quotes, are the cleanest way to embed JSON, XML or HTML snippets in code, because neither quotes nor backslashes need escaping, and the indentation of the closing delimiter is removed from every line.
Interpolation and formatting
String interpolation is the modern way to assemble text from values:
decimal total = 1234.5m;
DateTime due = new DateTime(2027, 1, 12);
string msg = $"Invoice total: {total:C2}, due {due:d}";
string padded = $"|{"left",-10}|{"right",10}|";
Inside the braces you can add an alignment after a comma and a format string after a colon, exactly as with string.Format. Microsoft's reference on string interpolation covers the details, including how interpolated strings can be combined with raw literals and verbatim strings.
The format result depends on the current culture: {total:C2} prints a euro amount on a French server and a dollar amount on an American one. In ASP.NET, the culture can come from the server, from web.config (<globalization culture="…">) or from the browser. For values meant for machines (logs, CSV, JSON, URLs), format with CultureInfo.InvariantCulture so that decimal separators do not change with the visitor.
Comparing strings safely
String comparison is where most subtle bugs hide. The rule from Microsoft's best practices for comparing strings is simple: always say which comparison you mean, by passing a StringComparison value.
// identifiers, file names, keys, HTTP headers: ordinal
if (string.Equals(role, "Admin", StringComparison.OrdinalIgnoreCase)) { … }
// text shown to and sorted for users: culture-aware
int order = string.Compare(a, b, StringComparison.CurrentCulture);
- Ordinal compares the raw code units. It is fast and predictable, and it is what you want for anything technical: role names, query string keys, file extensions, configuration values.
- Culture-aware comparison follows the linguistic rules of a language, which is right for sorting names in a list but can surprise you in security checks.
- Avoid comparing
ToUpper()orToLower()results: it allocates two new strings and behaves differently in some cultures. Use theIgnoreCasevariants instead.
Searching, slicing and splitting
The everyday methods are Contains, StartsWith, EndsWith, IndexOf and Substring; most of them accept a StringComparison too, and should get one. To break a string into parts, use Split:
string tags = "asp.net, c#, ,sql server";
string[] parts = tags.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
// ["asp.net", "c#", "sql server"]
Microsoft's how-to on dividing strings with Split shows the options for multiple separators and for limiting the number of parts. If the splitting happens in the browser instead, our article on splitting a string in JavaScript covers the client-side equivalent. For query strings, do not split by hand: Request.QueryString and HttpUtility.ParseQueryString decode values correctly, as explained in passing multiple QueryString parameters.
Building strings in loops
Because strings are immutable, concatenating inside a loop creates a new string at every pass. For a handful of pieces this does not matter, and string.Join or interpolation is clearer. For hundreds or thousands of pieces, such as an HTML table or a CSV export built row by row, use StringBuilder:
var sb = new StringBuilder();
foreach (DataRow row in table.Rows)
sb.Append(row["Name"]).Append(';').Append(row["Email"]).AppendLine();
string csv = sb.ToString();
Microsoft's page on using the StringBuilder class explains capacity and the cost of growing the buffer. The trade-offs, with measurements and ASP.NET examples, are in our comparison string vs StringBuilder.
Converting between strings and numbers
Form fields and query strings always arrive as text. Converting them is the most common string task in Web Forms code, and the safest pattern is TryParse:
if (int.TryParse(Request.QueryString["id"], out int id))
{
// use id
}
else
{
// missing or invalid: show a message, do not throw
}
int.Parse throws on bad input and Convert.ToInt32 returns zero for null, which can hide errors. The reference page for Int32.TryParse lists the overloads that take a NumberStyles and a culture, useful when users type thousands separators. In the other direction, ToString() with a format string ("N0", "D6", "F2") and a culture gives full control over the output.
Null, empty and whitespace
A text box left blank gives an empty string; a missing query string parameter gives null; a field full of spaces is neither. string.IsNullOrEmpty catches the first two, and string.IsNullOrWhiteSpace catches all three, which is usually what validation needs. Prefer string.Empty or "" to null when a method returns "no text", so callers do not need null checks everywhere.
Strings and security
Two habits protect an ASP.NET site from the classic string-based attacks. Never build SQL by concatenating user input: use parameters, as shown in our article on SQL injection. And encode text before writing it into a page (HttpUtility.HtmlEncode, or the <%: %> syntax in Web Forms), so that a comment field cannot inject a script.
Where to go next
The articles in this series go deeper on each topic: the difference between string and String, when StringBuilder pays off, splitting on the client, and reading strings that come from native C or C++ code, covered in our comparison of C and C++. Interpolation formats and string-to-number conversion will get their own detailed tutorials in the coming weeks.
string or String: is there a difference?
A question that comes up as soon as you read other people's code is whether to write string or String.
There is no difference in behaviour: string is a C# keyword that is an alias for the .NET type System.String. Both spellings compile to exactly the same thing. The choice is a matter of style, with one or two technical corners.
Same type
string a = "hello";
String b = "hello"; // needs 'using System;' (or global usings)
System.String c = "hello";
Console.WriteLine(a.GetType() == typeof(String)); // True
Console.WriteLine(typeof(string) == typeof(System.String)); // True
Static members are reachable through either name: string.IsNullOrEmpty(x) and String.IsNullOrEmpty(x) are the same call.
Where the spellings differ
- Scope.
stringis a keyword and always meansSystem.String.Stringis an ordinary type name, resolved throughusingdirectives; in theory a different type calledStringin your namespace would take precedence. - Without
using System;,Stringdoes not compile,stringdoes. Modern SDK projects add implicit global usings, so this rarely bites. - Keyword contexts. Only the keyword works where the language expects one, for example in some older syntaxes such as an enum's underlying type (
enum E : intrequires the keyword forint).
The other aliases
| C# keyword | .NET type |
|---|---|
string | System.String |
object | System.Object |
bool | System.Boolean |
int / long / short / byte | Int32 / Int64 / Int16 / Byte |
double / float / decimal | Double / Single / Decimal |
char | Char |
nint / nuint | IntPtr / UIntPtr |
The .NET name is useful in method names that describe a type, as the framework itself does: Convert.ToInt32, reader.GetInt64, not ToInt.
Which to use?
Microsoft's C# coding conventions recommend the language keywords (string, int) rather than the runtime type names for declarations and member access, and the default code-style rule IDE0049 in Visual Studio suggests the same. Some teams prefer String.Format for static calls; what matters is consistency within a code base, enforced by an .editorconfig setting.
For the wider picture (literals, interpolation, comparison, splitting and conversion), see our guide to working with strings in C#. A more substantial question about strings is mutability: see string vs StringBuilder.
A note on VB.NET
Visual Basic has the same arrangement: String (with a capital letter, as VB keywords are written) is a keyword alias for System.String, just as Integer maps to System.Int32. Code that mixes C# and VB.NET projects therefore uses one type throughout; only the spelling differs between the languages. In both, string comparison rules (ordinal, culture-aware, case-insensitive) matter far more in practice than which alias you type: pass a StringComparison value to Equals, StartsWith and IndexOf to make the intent explicit.
Reference documentation for this section: Built-in types (C# reference), The string type, C# coding conventions, IDE0049.
Sources
- Microsoft Learn, Strings and string literals (C# programming guide).
- Microsoft Learn, Raw string literal and String interpolation using $ (C# language reference).
- Microsoft Learn, Best practices for comparing strings in .NET.
- Microsoft Learn, Divide strings using String.Split, Using the StringBuilder class, Int32.TryParse.