Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Guid from an int

Tags:

c#

guid

Given an int, how can you create the same Guid repeatedly?

Edit:
I'm integrating two systems, one uses ints as a primary key, the other recognises an object by it's Guid. Because of this, I need to be able to recreate the same Guid for a given int so that the second system can recognise the entities coming from the first.

like image 649
Greg B Avatar asked Jul 21 '10 21:07

Greg B


2 Answers

If you want the guid to consist of just the int then:

int x = 5;
string padded = x.ToString().PadLeft(32,'0');
var intGuid = new Guid(padded);

intGuid.ToString(); // 00000000-0000-0000-0000-000000000005
like image 115
STW Avatar answered Oct 26 '22 13:10

STW


If you create a Guid based on an integer it will no longer be a globally unique identifier.

Having said that you can use the constructor that takes an integer and some other parameters:

int a = 5;
Guid guid = new Guid(a, 0, 0, new byte[8]);

Not really advisable...

like image 41
Mark Byers Avatar answered Oct 26 '22 12:10

Mark Byers