Guid.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)
System.Guid desiredGuid = 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
.
Alternately, if you are using SQL Server as your database you can get your GUID from the server instead. In TSQL:
//Retrive your key ID on the bases of GUID
declare @ID as uniqueidentifier
SET @ID=NEWID()
insert into Sector(Sector,CID)
Values ('Diry7',@ID)
select SECTORID from sector where CID=@ID
There'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
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.
Guid.NewGuid()
creates a new random guid.
To 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 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());
}
Source: Stackoverflow.com