Generating GUIDs with .Net
When Windows developers need a unique value, they often utilize a Globally Unique Identifier (GUID). Microsoft uses the term GUID for a unique number that identifies an entity, such as a Word document.
A GUID is a 128-bit integer (16 bytes) that you can use across all computers and networks wherever a unique identifier is required. There's a very low probability that this type of identifier will be duplicated.
This article explains how the .NET Framework makes it possible for you to create your own GUID.
GUIDs are used throughout the Windows environment. When you peruse the registry on a Windows system, you can see that GUIDs are used extensively to uniquely identify applications and so forth. In particular, they serve as application IDs under the HKEY_CLASSES_ROOT section (AppID key).
This is the format of a typical GUID:
Possessing a unique identifier makes it easy to store and retrieve information. This is especially useful when working with a database because a GUID makes an excellent primary key.
Also, SQL Server integrates well with GUID usage. The SQL Server data type uniqueidentifier stores a GUID value. You can either generate this value within SQL Server—using the NEWID() function—or you can generate the GUID outside of SQL Server and insert it manually.
The latter approach is a straightforward process in .NET. The base System class in the .NET Framework includes the GUID value type. In addition, this value type includes methods to work with GUID values. In particular, the NewGUID method allows you to easily generate a new GUID.
The following C# command-line application shows how it's used:
At this point, you may be thinking that GUIDs are a nice feature, but how and where would you use them in your applications?
A GUID makes a great primary key in a back-end database. The example in Listing A uses a GUID to store information in a back-end database, which has the following columns: pk_guid (uniqueidentifier data type) and name (nvarchar data type). A simple Windows form is presented with one text box. The data from the text box is inserted into the database table when a button is selected. A GUID is generated by the application code and stored in the other column.
Another GUID application is assigning a unique identifier to a .NET class or interface; that is, the GUID is assigned as an attribute for the class or interface. This is accomplished using the standard attribute syntax.
We can extend our first example to assign a GUID to it. The System.Runtime.InteropServices namespace must be referenced to utilize the GUID attribute. The following C# code does that:
As with most aspects of development, the .NET Framework simplifies the process of creating and working with GUID values. This makes it easy to generate unique values where necessary in your .NET application.
|All times are GMT +5.5. The time now is 05:34.|