Search code examples
c#google-mapsuuidguid

How to generate UUID version 4 using c#


My requirement is to generate version 4 UUID from C# code for google API session token and i am not sure Guid.NewGuid() method, Which version of GUID does it return. Like version

Read google and blog but not get sure answer Does Guid.NewGuid() produce UUID version 4 according to RFC4122?

Thanks in advance


Solution

  • GUIDs are V4... every single GUID you generate will look like this

    18acac20-991e-437e-9529-a441452f6b7e
    d6d68639-64c2-452e-95b7-16cf6dbf5301
    b0943b6d-4779-4771-92bf-cc2d634fb671
    218b5620-d30d-46d9-9c88-38a4ac64266e
    de03042c-792f-4689-80ca-26287ceb2129
    1175bb5d-d35e-4a46-aaac-0825c749dc3a
    42864583-c0f6-4e44-8710-39c9a9146d43
    223ca924-4b77-4931-bb94-c1d371894683
    2c4495ab-19e4-4aeb-b647-10db8625791c
    f5894345-cbe3-4fc7-92c3-d6d863f70411
                  ^    ^
                  1    2
    

    The digit at position 1 above is always 4 and the digit at position 2 is always one of 8, 9, A or B.

    You can confirm this by

    var cts = new CancellationTokenSource();
    
    var parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = 8, CancellationToken = cts.Token };
    Parallel.For(0, int.MaxValue, parallelOptions, (i) =>
    {
        var guid = Guid.NewGuid().ToString();
        var four = guid.ElementAt(14);
        var ab89 = guid.ElementAt(19);
    
        if (four != '4') cts.Cancel();
        if (ab89 != 'a' && ab89 != 'b' && ab89 != '8' && ab89 != '9') cts.Cancel();
    
        if ((i % 100000) == 0 && i < (int.MaxValue / 8))
        {
            Console.WriteLine($"{i * 8:n}"); // roughly   
        }
    });
    

    That will run through 4billion'ish attempts in a reasonable amount of time if you have doubts