.Net ramblings
# Tuesday, 15 March 2005
HowTo: get a random letter in C#
public static char GetRandomLowerCaseCharacter(int seed)
   return ((char) ( (short) 'a' + new Random(seed).Next(26)));

public static char GetRandomUpperCaseCharacter(int seed)
   return ((char) ( (short) 'A' + new Random(seed).Next(26)));

If you call the above methods straight after each other with the same seed, you may get the same value on a fast processor.  It is a good reason to pass in a different seed value for operations that will be done in quick succession.  E.g. use DateTime.Now.Seconds for one operation and then use Minutes or Hour or Milliseconds for the next ones.

Tuesday, 15 March 2005 18:26:27 (GMT Standard Time, UTC+00:00)  #    Comments [2]  .Net General

Thursday, 08 July 2010 22:43:25 (GMT Daylight Time, UTC+01:00)
You should create a new instance of the Random class outside of the function and then pass that into the function instead of the seed. You shouldn't re-seed the the Random class for each call to it in a loop. An example:

string code = string.Empty;

for (int i = 1; i < 6; i++)
code += ((char)((short)'A' + random.Next(26)));
John Vogel
Friday, 27 May 2011 18:51:38 (GMT Daylight Time, UTC+01:00)
This helped me out, thanks!
Please login with either your OpenID above, or your details below.
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview