Developer

Generating GUIDs with VB.NET

There are a variety of reasons why developers use globally unique identifiers (GUIDs), such as assigning unique identifiers to classes or when dealing with databases. This tip contains sample code that shows you how to generate GUIDs with VB.NET.

Developers use globally unique identifiers (GUIDs) for various reasons, such as assigning unique identifiers to classes or when dealing with databases. GUIDs are the Microsoft implementation of the distributed computing environment (DCE) universally unique identifier (UUID). GUIDs are 128-bit globally unique identifiers that are automatically generated based on close to two zillion frequently varying factors.

There is an extremely low possibility that the value of GUID would be all zeroes, or that it would be equal to any other GUID. You can use GUIDs across all computers and networks wherever a unique identifier is required.

GUIDs identify objects such as interfaces and class objects. A GUID consists of one group of 8 hexadecimal digits, followed by three groups of 4 hexadecimal digits each, which are followed by one group of 12 hexadecimal digits.

In the following script, I manually generate the GUID that I can use later in the application by using VB.NET:

Private Sub GenerateGUID()

        Dim sGUID As String
        sGUID = System.Guid.NewGuid.ToString()
        MessageBox.Show(sGUID)

    End Sub

In the example, I define a string variable, sGUID, to hold a GUID that I will generate. Then I set the value of sGUID to the value returned by the System.Guid.NewGuid method (using the System.Guid namespace) and convert the result to a string using ToString(). The result is displayed in a message box.

Note: Visual Studio .NET allows you to easily generate GUID interactively by running the Visual Studio .NET Command Prompt. For more details, visit the MSDN site. Another resource to check out is the TechRepublic article, "Generating and working with GUIDs in .NET."

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Irina Medvinskaya's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

2 comments
washcaps
washcaps

Would you store this as a Varchar in SQL then? thx, seed

Josharghhhh
Josharghhhh

in powershell this would be 15> $sGUID = [System.Guid]::NewGuid() 16> $sGUID.ToString()

Editor's Picks