четверг, 18 марта 2010 г.

Random in C#

This code is wrong example of using Random class. Each element of the arr will be the same.
And don't trust the Debug mode! Because in Debug mode with breakpoints you will see different values each time.

  1. int[] arr = new int[count];
  2.  
  3. for (int j = 0; j < count; j++)
  4. {
  5.   Random rnd = new Random();
  6.  
  7.   arr[j] = rnd.Next(int.MaxValue);
  8. }
* This source code was highlighted with Source Code Highlighter.

Use this one! good Example below:

  1. int[] arr = new int[count];
  2. Random rnd = new Random();
  3.  
  4. for (int j = 0; j < count; j++)
  5. {
  6.   arr[j] = rnd.Next(int.MaxValue);
  7. }
* This source code was highlighted with Source Code Highlighter.

1 комментарий:

  1. ваще-то уж если совсем по правильному то:

    new Random(unchecked((int) (DateTime.Now.Ticks))

    ОтветитьУдалить