1

I have a string which identifies a customer. On my website, I have 3 different images for customers who have not set a profile picture. I want to randomly associate one of these images to a customer, but not have the image change between sessions.

Is there any problems with using GetHashCode, like in the following code?

switch (CustomerIdString.GetHashCode() % 3)
{
    case 0:
        return "NoProfileImage0.png";
        break;

    case 1:
        return "NoProfileImage1.png";
        break;

    case 2:
    default:
        return "NoProfileImage2.png";
        break;
}

I understand there are other solutions, such as-

  • Use a better hashing library
  • Use the customer id as the seed in a random number generator
  • Persist the image name against the customer record

but I like the simplicity (no added libraries, no DB code) of using GetHashCode().

riQQ
  • 9,878
  • 7
  • 49
  • 66
Spongeboy
  • 2,232
  • 3
  • 28
  • 37

3 Answers3

1

I found your example code useful in my application as I'm doing something similar. However, I found I needed to use Math.Abs around GetHashCode as it sometimes returns negative numbers:

Math.Abs(String.GetHashCode()) Mod 3

(Apologies that my reply is in vb.net rather than c#)

Simon White
  • 789
  • 2
  • 8
  • 16
1

Related: Can I depend on the values of GetHashCode() to be consistent?

Basically,string.GetHashCode is not guaranteed to be the same across versions of the .NET framework.

You might want to consider using a hash function that exists in the broader scope outside of .NET (yet still is implemented in .NET!) and has an associated specification, for example MD5. That will make your software more portable and resilient.

For how to get a MD5 hash, see related: MD5 Hash From String

Community
  • 1
  • 1
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
0

I don't see any issues with that, although it won't be random at all, it will always be the same image based on the value for CustomerIdString.

Andy
  • 8,432
  • 6
  • 38
  • 76
  • The aim is for it to be random amongst users, but consistent for each user. – Spongeboy May 29 '13 at 01:09
  • Random is not the word you want; you want to chose a discrete item from a set, there's no randomness involved. I know it seems nitpicky, but being clear about this kind of thing is important in our industry. – Andy May 29 '13 at 01:30