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#:

  1. using System;
  2.  
  3. namespace GuidGenerator {
  4.     class Program {
  5.         static void Main(string[] args) {
  6.             var guid = Guid.NewGuid();
  7.             Console.WriteLine("Your GUID is: " + guid.ToString());
  8.         }
  9.     }
  10. }

Explanation

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:

  1. using System;
  2.  
  3. namespace GuidGenerator {
  4.     class Program {
  5.         static void Main(string[] args) {
  6.             var guidAsString = "032c99b2-d17e-41f6-9259-1f70958dc106";
  7.             var guid = new Guid(guidAsString);
  8.             Console.WriteLine("Your GUID is: " + guid.ToString());
  9.         }
  10.     }
  11. }

Explanation