Generate a UUID in Visual Basic .NET
Visual Basic .NET (VB.NET) is a programming language developed by Microsoft as the successor to the original Visual Basic language.
As its name implies, VB.NET is implemented on Microsoft's .NET Framework - one of the original 2 languages (along with C#) developed by Microsoft for their .NET Framework. Like C#, it is an object-oriented, statically-typed, general-purpose programming language used in many different domains, but is run almost exclusively on Windows computers.
How to Generate a UUID in VB.NET
The VB.NET 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 VB.NET code.
Imports System.DiagnosticsModule Module1Sub Main()Dim myuuid As Guid = Guid.NewGuid()Dim myuuidAsString As String = myuuid.ToString()Debug.WriteLine("Your UUID is: " & myuuidAsString)End SubEnd Module
Explanation
- On line #5, we use the
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 #6, we use the
ToString()
method to convert theGuid
instance to a String. The String representation of aGuid
looks like a standard UUID (i.e. 9d68bfe1-4d92-4054-9c8f-f3ec267c78fb). 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 #8 will be something like:
Your UUID is: 9d68bfe1-4d92-4054-9c8f-f3ec267c78fb
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 #6 above) back into an instance of Guid
.
VB.NET provides for this scenario with a Guid
constructor,
Guid(string)
.
You can call this method like this:
Imports System.DiagnosticsModule Module1Sub Main()Dim myuuid As Guid = Guid.NewGuid()Dim myuuidAsString As String = myuuid.ToString()Dim sameUuid As New Guid(myuuidAsString)Debug.Assert(sameUuid.Equals(myuuid))End SubEnd Module
Explanation
- Line #8 shows converting the string representation of a UUID into a
Guid
instance (sameUuid
) using theGuid(String)
constructor method. - Line #9 is included to show that the 2
Guid
instances are equal.
How can we improve this page? Let us know!