Languages
[Edit]
EN

C# / .NET - create GUID value

4 points
Created by:
AnnLen
9180

In C# / .NET it is possible to create GUID / UUID (Globally Unique Identifier / Universally Unique Identifier) in the following way.

1. Guid.NewGuid + Giud.ToString methods example

Guid guid = Guid.NewGuid();
string text = guid.ToString();

Console.WriteLine(text);

Output:

805036a5-254b-49f5-aef5-9b66255da3e3

2. Guid.NewGuid + Guid.ToByteArray methods example

Guid guid = Guid.NewGuid();
byte[] bytes = guid.ToByteArray();

foreach(byte entry in bytes)
	Console.Write(entry + " ");

Console.WriteLine();

Output:

165 54 80 128 75 37 245 73 174 245 155 102 37 93 163 227

3. Custom GUID example

Guid guid = new Guid(new byte[]
{
	0x00, 0x01, 0x02, 0x03,
	0x04, 0x05,
	0x06, 0x07,
	0x08, 0x09,
	0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
});

Console.WriteLine(guid.ToString());

Output:

03020100-0504-0706-0809-0a0b0c0d0e0f
Note: order of first 8 bytes is different than in string. It is caused of Microsoft GUID implementation and Little-endian of x86 processors compatibility:
typedef struct _GUID {
	DWORD Data1;
	WORD  Data2;
	WORD  Data3;
	BYTE  Data4[8];
} GUID;
It means DWORD and WORD bytes are reversed.

3. References

  1. Guid.NewGuid Method - Microsoft Docs
  2. Endianness - Wikipedia
  3. GUID Struct - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join