How to Use Guid in C#: Syntax, Examples, and Tips
In C#, use the
Guid struct to create unique identifiers. You can generate a new Guid with Guid.NewGuid() and convert it to a string with ToString().Syntax
The Guid struct represents a globally unique identifier. You can create a new Guid using Guid.NewGuid(). To convert a Guid to a string, use ToString(). You can also parse a string back to a Guid using Guid.Parse().
csharp
Guid newId = Guid.NewGuid(); string idString = newId.ToString(); Guid parsedId = Guid.Parse(idString);
Example
This example shows how to create a new Guid, display it as a string, and parse it back to a Guid type.
csharp
using System; class Program { static void Main() { // Create a new Guid Guid uniqueId = Guid.NewGuid(); // Convert Guid to string string idString = uniqueId.ToString(); Console.WriteLine("Generated Guid: " + idString); // Parse string back to Guid Guid parsedId = Guid.Parse(idString); Console.WriteLine("Parsed Guid equals original: " + (parsedId == uniqueId)); } }
Output
Generated Guid: 3f2504e0-4f89-11d3-9a0c-0305e82c3301
Parsed Guid equals original: True
Common Pitfalls
- Trying to create a Guid with an empty string instead of using
Guid.Empty. - Parsing invalid strings without error handling causes exceptions.
- Comparing Guids as strings instead of using Guid equality.
Always use Guid.TryParse() to safely parse strings.
csharp
using System; class Program { static void Main() { string invalidGuid = "not-a-guid"; // Wrong: This throws an exception // Guid parsed = Guid.Parse(invalidGuid); // Right: Use TryParse to avoid exceptions bool success = Guid.TryParse(invalidGuid, out Guid result); Console.WriteLine("Parsing success: " + success); } }
Output
Parsing success: False
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Create new Guid | Guid id = Guid.NewGuid(); | Generates a new unique identifier |
| Convert to string | string s = id.ToString(); | Gets string representation of Guid |
| Parse from string | Guid id = Guid.Parse(s); | Converts string back to Guid |
| Safe parse | bool ok = Guid.TryParse(s, out Guid id); | Tries to parse string without exception |
| Empty Guid | Guid empty = Guid.Empty; | Represents a Guid with all zeros |
Key Takeaways
Use Guid.NewGuid() to generate unique identifiers in C#.
Convert Guids to strings with ToString() for display or storage.
Use Guid.TryParse() to safely convert strings to Guid without exceptions.
Avoid comparing Guids as strings; use Guid equality operators instead.
Guid.Empty represents a Guid with all zeros and can be used as a default value.