One field of our struct is Guid type. How to generate a valid value for it?
11 Answers
Guid id = Guid.NewGuid(); 3Guid.NewGuid() creates a new random guid.
There are two ways
var guid = Guid.NewGuid(); or
var guid = Guid.NewGuid().ToString(); both use the Guid class, the first creates a Guid Object, the second a Guid string.
2Guid.NewGuid() will create one
var guid = new Guid(); Hey, its a 'valid', although not very useful, Guid.
(the guid is all zeros, if you don't know. Sometimes this is needed to indicate no guid, in cases where you don't want to use a nullable Guid)
7To makes an "empty" all-0 guid like 00000000-0000-0000-0000-000000000000.
var makeAllZeroGuID = new System.Guid(); or
var makeAllZeroGuID = System.Guid.Empty; To makes an actual guid with a unique value, what you probably want.
var uniqueGuID = System.Guid.NewGuid(); If you want to create a "desired" Guid you can do
var tempGuid = Guid.Parse("<guidValue>"); where <guidValue> would be something like 1A3B944E-3632-467B-A53A-206305310BAE.
System.Guid desiredGuid = System.Guid.NewGuid(); 2There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.
PM> Install-Package CSharpVitamins.ShortGuid Usage:
Guid guid = Guid.NewGuid(); ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid Console.WriteLine(sguid1); Console.WriteLine(sguid1.Guid); This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:
ShortGuid: FEx1sZbSD0ugmgMAF_RGHw Guid: b1754c14-d296-4b0f-a09a-030017f4461f If you are using this in the Reflection C#, you can get the guid from the property attribute as follows
var propertyAttributes= property.GetCustomAttributes(); foreach(var attribute in propertyAttributes) { var myguid= Guid.Parse(attribute.Id.ToString()); } It's really easy. The .Net framework provides an in-built function to create and parse GUIDS. This is available in the System namespace and the static Guid class.
To create a GUID just use the code below:
var newGuid = System.Guid.NewGuid(); To parse a GUID string as a GUID, use the code below:
var parsedGuid = System.Guid.Parse(guidString); If you just want to create a new guide and just use it in your application, just use one of the online GUID Generator tools online to create yourself a new guid.