sukesh
sukesh

Reputation: 2523

Uniqueness for a shortened guid

I have to append a unique code as a querystring, for every url generated. So, the option I chose is to shorten a guid (found here on SO).

public static string CreateGuid()
        {          

          Guid guid = Guid.NewGuid();
            return Convert.ToBase64String(guid.ToByteArray());
        }

Will this be as unique as a guid, cause I have several urls to generate and this guid will be saved in DB.

Upvotes: 1

Views: 339

Answers (2)

welegan
welegan

Reputation: 3043

You should watch out if you are using this in the url. While the string will be shorter, it will potentially have characters that are illegal in urls, so you may need to run it past

HttpUtility.UrlEncode()

to be safe. Of course, once you do that, it will get a little longer again.

Edit:

Your comment makes it seem like you want some sort of math, so here goes:

Let's assume that you have 24 alphanumeric characters all the time, and casing does not matter. That means each character can be 0-9 + a-z or 36 possibilities. That makes it 24 ^ 36 different possible strings. Refer to this website then:

http://davidjohnstone.net/pages/hash-collision-probability

Which lets you plug in possible values and the number of times you will need to run your code. 24^36 is equivalent to 2^100 (I arrived at this number after some googling, may be incorrect). plugging in 100 into the "number of bits in your hash" field at the link above means if you run your code 1000000 times, you will still only have 3.944300×10^19 odds of a collision, or the same value coming up twice. That's miniscule, but you may run into issues if you are writing something that will be used many many more times than that.

Upvotes: 1

Robert Levy
Robert Levy

Reputation: 29073

Yup, the default string representation of a guid is base16. By reformatting the same value as base64, you get a shorter (but possibly uglier) string.

Upvotes: 2

Related Questions