How to generate a GUID in C#
C# is a strongly typed object-oriented programming language and is part of the .NET framework. The C# programming language is one of the most popular programming languages in the world and it is developed by Microsoft. C# it is open source and runs on MacOS, Linux and Windows operating systems.
The C# language has built in support for generating GUIDs. Below is an example of how to generate a GUID in C#:
- using System;
- namespace GuidGenerator {
- class Program {
- static void Main(string[] args) {
- var guid = Guid.NewGuid();
- Console.WriteLine("Your GUID is: " + guid.ToString());
- }
- }
- }
Explanation
- On line #6, we declare a variable named guid and we use the Guid.NewGuid() static method to create a new GUID instance.
- On line #7, we use the Console.WriteLine() method to output the GUID value to console. We use the ToString() method to convert the GUID instance to a string.
- The output of the above program will be something similar to this one:
- Your GUID is: 032c99b2-d17e-41f6-9259-1f70958dc106
How to convert from a string to GUID in C#
Sometimes you might need to convert from a string representation of GUID back to an instance of Guid. C# has also built-in support to for this case:
- using System;
- namespace GuidGenerator {
- class Program {
- static void Main(string[] args) {
- var guidAsString = "032c99b2-d17e-41f6-9259-1f70958dc106";
- var guid = new Guid(guidAsString);
- Console.WriteLine("Your GUID is: " + guid.ToString());
- }
- }
- }
Explanation
- On line #6, we declare a variable of type string named guidAsString and we set its value to a string representation of a Guid.
- On line #7, we declare a variable of type Guid and we use it's constructor to instantiate it. The constructor takes the above variable as a parameter.
- The output of the above program will be something similar to this one:
- Your GUID is: 032c99b2-d17e-41f6-9259-1f70958dc106