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
- On line #5, we use the
Guid.NewGuid()static method to create a new
Guidinstance, 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 the
Guidinstance to a String. The String representation of a
Guidlooks 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 the
myuuidinstance, rather than the
- 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
VB.NET provides for this scenario with a
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
- Line #8 shows converting the string representation of a UUID into a
sameUuid) using the
- Line #9 is included to show that the 2
Guidinstances are equal.
How can we improve this page? Let us know!