Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a random GUID in C# within a specified interval

Tags:

c#

guid

Using the .NET Framework, is there a way to create a random GUID in C# within a specified interval? For example, I need a random GUID that is greater than ffffffff-ffff-ffff-ffff-1fffffffffffff and less than ffffffff-ffff-ffff-ffff-2fffffffffffff.

like image 710
Mark13426 Avatar asked Oct 16 '12 03:10

Mark13426


People also ask

How do you generate a random GUID?

To Generate a GUID in Windows 10 with PowerShell, Type or copy-paste the following command: [guid]::NewGuid() . This will produce a new GUID in the output. Alternatively, you can run the command '{'+[guid]::NewGuid(). ToString()+'}' to get a new GUID in the traditional Registry format.

What is GUID NewGuid ()?

Guid. NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

Can you generate the same GUID?

It's possible to generate an identical guid over and over. However, the chances of it happening are so low that you can assume they are unique.


1 Answers

Use this overload:

[CLSCompliantAttribute(false)]
public Guid(
    uint a,
    ushort b,
    ushort c,
    byte d,
    byte e,
    byte f,
    byte g,
    byte h,
    byte i,
    byte j,
    byte k
)

Guid(0xa,0xb,0xc,0,1,2,3,4,5,6,7) creates a Guid that corresponds to:

0000000a-000b-000c-0001-020304050607

You can randomize the parameters any way you like. For example, you can do:

var r[] = new byte[] { 1,2,3,4 } // chosen by fair dice rolls
                                 // guaranteed to be random

var guid = new GUID(0xFFFFFFFF, 0xFFFF, 0xFFFF, 0xFFFF, r[1], r[2], r[3], r[4]...

Well, you get the idea. You have to do some bit twiddling to get the fifth parameter right.

like image 93
Robert Harvey Avatar answered Sep 29 '22 10:09

Robert Harvey