---
title: "Random Number Generator issue in C#"  
description: "Random Number Generator issue in C#"  
author: "E E Cummings"  
published: 2013-10-14  
updated: 2013-10-14  
canonical: https://www.mindstick.com/forum/1671/random-number-generator-issue-in-c-sharp  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# Random Number Generator issue in C#

I want to [add](https://www.mindstick.com/forum/12983/add-address-in-textbox-when-page-is-load-and-if-i-search-address-in-textbox-show-in-map-by-javascript) a random number to a list to be used as a ID number and then exports it to Excel. However i cam across a probelm when using more than 2 [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) members in my datafile: The [Random numbers](https://www.mindstick.com/forum/832/generate-random-numbers-uniformly-over-entire-range) i generate double up, causing my [program](https://www.mindstick.com/blog/12337/scaling-up-your-mentorship-program) to crash.

\

```
static Dictionary<string,Backup> getData(){    Dictionary<string, Backup> bDict = new Dictionary<string, Backup>();    StreamReader reader = new StreamReader("/data/storedata.txt");    while (!reader.EndOfStream)    {        string line = reader.ReadLine();        string[] parts = line.Split(' ');        string item = parts[0];        string owner = parts[1];        Random rnd = new Random();        int test = rnd.Next(item.Length+10000);//For every 'item' a Random number is generated.(the +10000 is simply to produce a 4-digit number)        //Console.WriteLine(test);//Testing         Backup BP = new Backup(item, owner,test);        bDict.Add(test.ToString(), BP);//Adding to the Dictionary.        //Console.WriteLine(string.Format("{0}, {1}, {2}", item, test, owner));    }    return bDict;}//Read file, Grabed data and stored it in a List.
```

## Replies

### Reply by Andrew Deniel

The [Random](https://www.mindstick.com/forum/33419/generating-random-numbers-in-objective-c) numbers i generate double up, causing my program to crash.

You just have to check if the number already exists in the Dictionary:

while(bDict.ContainsKey(test.ToString()))

test = rnd.Next(item.Length + 10000);


---

Original Source: https://www.mindstick.com/forum/1671/random-number-generator-issue-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
