Generate a UUID in C#
C# is one of the more popular programming languages in the world.
Based on Microsoft's .NET framework, C# was first available in 2000. It is a general-purpose, object-oriented, strongly typed programming language that is used in both frontend and backend applications. Because of its relationship to Microsoft's .NET framework, it is most often used in applications that run on Windows.
How to Generate a UUID in C#
The C# language, via the .NET Framework, has built-in support for generating Version 4 UUIDs. Here's an example of how you can create a UUID in C# code.
using System;using System.Diagnostics;namespace SampleApplication {class Program {static void Main(string[] args) {Guid myuuid = Guid.NewGuid();string myuuidAsString = myuuid.ToString();Debug.WriteLine("Your UUID is: " + myuuidAsString);}}}
Explanation
- On line #7, we use the
System.Guid.NewGuid()
static method to create a newGuid
instance, stored in the variable,myuuid
. In .NET, a GUID (Globally Unique Identifier) is equivalent to a UUID. - On line #8, we use the
ToString()
method to convert theGuid
instance to a string. The string representation of aGuid
looks like a standard UUID (i.e. 2e63341a-e627-48ac-bb1a-9d56e2e9cc4f). If you're going to store the UUID in a file, database or model property, or send it via an API call to a different application, you'll almost always need the string representation of themyuuid
instance, rather than themyuuid
instance itself. - The output from line #10 will be something like:
Your UUID is: 2e63341a-e627-48ac-bb1a-9d56e2e9cc4f
Convert from a string to a UUID
Although it's rare, in some circumstances you might need to convert from a string representation of a UUID (like the
one from line #8 above) back into an instance of Guid
.
C# provides for this scenario with a Guid
constructor,
Guid(string)
.
You can call this method like this:
using System;using System.Diagnostics;namespace SampleApplication {class Program {static void Main(string[] args) {Guid myuuid = Guid.NewGuid();string myuuidAsString = myuuid.ToString();Guid sameUuid = new Guid(myuuidAsString);Debug.Assert(sameUuid.Equals(myuuid));}}}
Explanation
- Line #10 shows converting the string representation of a UUID into a
Guid
instance (sameUuid
) using theGuid(String)
constructor method. - Line #11 is included to show that the 2
Guid
instances are equal.
How can we improve this page? Let us know!