---
title: "Random number generator only generating one random number"  
description: "Random number generator only generating one random number"  
author: "Anonymous User"  
published: 2013-05-29  
updated: 2013-05-29  
canonical: https://www.mindstick.com/forum/929/random-number-generator-only-generating-one-random-number  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Random number generator only generating one random number

Hi,\
I have the following [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server):\
//Function to get [random](https://www.mindstick.com/forum/33419/generating-random-numbers-in-objective-c) number[public](https://www.mindstick.com/blog/11097/java-access-modifiers-the-public-and-the-private-modifiers) [static](https://www.mindstick.com/articles/12098/the-static-keyword-the-static-methods) int RandomNumber(int min, int max){ Random random = new Random(); return random.Next(min, max);}\
I'm [trying](https://answers.mindstick.com/qa/93698/6-mistakes-couples-are-trying-to-save-money) as following\
byte[] [mac](https://www.mindstick.com/articles/311752/how-to-install-and-use-the-google-wifi-software-on-a-windows-or-mac-computer) = new byte[6];for (int x = 0; x < 6; ++x) mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);\
If I step that loop with the debugger during run time I get different [values](https://www.mindstick.com/forum/327/sum-textbox-values) (which is what I want). However, if I put a break point two lines below that [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii), all members of the "mac" [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net) have equal value.\
Please [resolve](https://www.mindstick.com/forum/159427/windows-app-dll-not-found-resolve-library-issue) my problem.Thanks in advance. \

## Replies

### Reply by AVADHESH PATEL

Hi Goti!\
Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.\
//Function to get random numberprivate static readonly Random random = new Random();private static readonly object syncLock = new object();public static int RandomNumber(int min, int max){ lock(syncLock) { // synchronize return random.Next(min, max); }}\


---

Original Source: https://www.mindstick.com/forum/929/random-number-generator-only-generating-one-random-number

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
