I've a line in the bottom part of the main screen of the game, that every time the scene is loaded, it shows a different tip (how to play, how to change music...).
The question is that I'm using Random.Range for that but, honestly, I'll prefer a way where all tips are showed, one by one in a random way, but without repeating any of them.
My code is as follows:
int randNum;
void Start () {
randNum = Random.Range(0,5);
}
void Update () {
switch (randNum)
{
case 0:
// blah, blah, blah...
case 1...
How can I achieve what I want?
Thans for yout timeeee :)
You can remove the switch statement and store each message in a list.
var tips = new List<string>();
tips.Add("The clouds are white");
...
Then you can randomize the elements in the list (more on that here) and show tips one by one. All you need is to keep track of the index. Example:
// This needs to be a field.
int index = 0;
void ShowTip()
{
// TODO: make sure index is not equal or greater than tips.Count
tip = tips[index];
index++;
// Display the tip
}
What you can do is to shuffle your list of tip. The Fisher-Yates shuffle is one of the most common.
static Random _random = new Random();
static void Shuffle<T>(T[] array)
{
int n = array.Length;
for (int i = 0; i < n; i++)
{
// Use Next on random instance with an argument.
// ... The argument is an exclusive bound.
// So we will not go past the end of the array.
int r = i + _random.Next(n - i);
T t = array[r];
array[r] = array[i];
array[i] = t;
}
}
public static void Main()
{
string[] array = { "tip 1", "tip 2", "tip 3" };
Shuffle(array);
foreach (string value in array)
{
Console.WriteLine(value);
}
}
output
net
dot
perls
source
Suppose your messages are stored in a list of string declared at the global level together with your random class and with an additional List of strings initially empty
List<string> needToDisplayMessages = new List<string>();
List<string> base_messages = new List<string>{"message1","message2","message3","message4","message5"};
Random rnd = new Random();
In your update method check if the list of messages to be displayed is empty and if yes copy the messages from the list with the predefined message. Now use the random instance to choose the index of the message to display and get it from the dynamic list. Finally remove the message from the list of message still to be displayed.
void Update () {
// We refill the list if it is empty
if(needToDisplayMessages.Count == 0)
needToDisplayMessages.AddRange(base_messages);
// Choose a random number topped by the count of messages still to be displayed
int index = rnd.Next(0, needToDisplayMessages.Count);
string message = needToDisplayMessages[index];
..... display the message someway .....
// Remove the message from the list
needToDisplayMessages.RemoveAt(index);
}
Of course, if you want to display the messages in sequential order there is no need of this but (as already explained) just an index. But if you want to randomly choose the message until you have shown all of them and then restart the cycle, perhaps this approach is not too much complex.
Related
I am implementing this code in my discord bot, where I want to be able to generate unique numbers from 1 to 10 (as suggested above) whenever I input a single command.
Turns out that the values sometimes are repeated. Therefore I was suggested to add an array (used[ ]) and a loop in order to check every time if the value has been generated already.
Random random = new Random();
int[] used = new int[10];
int rng = 0;
while (!used.Contains(rng))
{
rng = random.Next(1, 10);
}
/*
I wish to store the generated value "rng" to the "used" array.
e.g.
used[0] = rng
used[1] = rng
used[2] = rng
etc.
*/
Console.WriteLine("The number generated is " + Convert.ToString(rng));
However, I don't know how to constantly add values to an array in an arranged order. (as seen by the commentations above)
In a more simple way, For 10 times I want the system to generate a number, and those numbers are randomly picked out of [1,10] and only once. If all the numbers have been generated once, all are free to be generated again.
Sorry for my bad interpretation. I have refined it with the comments that everyone has contributed.
Here is a solution, that shuffles the values and returns each value until the list is exhausted, then starts all over:
int[] GenerateNewArray(int n)
{
// Define an array of values we wish to return and populate it
int[] baseValues = Enumerable.Range(1, n).ToArray();
Random rnd=new Random();
// Shuffle the array randomly using Linq
return baseValues.OrderBy(x => rnd.Next()).ToArray();
}
void Main()
{
int nNumbers = 10;
while (true)
{
// Generate a new randomized array
var values = GenerateNewArray(nNumbers);
// Print each value
for (int i=0;i<nNumbers;i++)
{
Console.WriteLine($"The number generated is {values[i]}");
}
}
}
EDIT
Parameterized the number of unique values.
Rather than storing in an array, looking for duplicates etc., just use a HashSet
This only accepts unique values, and if you try to add a duplicate it will be simply ignored.
Or you can just do a check to see if it exists
HashSet<int> integerSet = new HashSet<int>();
if (hashSet.Contains(rng ))
// element already exists in set
else
//Doesn't exist
Of course, if you just keep generating each number randomly until you have generated everything in the range, then you might as well just simply generate an array/list of elements with every number and save yourself processing time!
Using a list is a good way to start, but before continuing the comment go check out the list documentation
In small talk a list is an IEnumerable of a type you choose, in your case to declare and instanciate a list you should write like this List<int> listName = new List<int>(); and the main difference between an array and a list is that you can populate the list whenever you want without the length declaration, to do that you can add listName.Add(2); (2 : the integer value that you want to add) or remove values listName.Remove(0) (0 : the position of the list that need to be removed, ex: 0 is the first value inside the list because position 0 is the start)
Random random = new Random();
List<int> listName = new List<int>();
int rng = 0, counterOfValues = 0;
while (counterOfValues < 10)
{
rng = random.Next(1, 10);
If(!listName.Contains(rng))
{
listName.Add(rng);
Console.WriteLine("The number generated is " + listName.Last().ToString());
If(counterOfValues < 10)
{
counterOfValues++;
}
else
{
counterOfValues = 0;
}
}
}
This should probably do the work ("should" because it's some code I wrote out of my head, so sorry about caps ecc)
Let me know if it works as intended or we need to correct something!
P.S: If you want the user to select the range of the randomic values just change the value of counterOfValues in the lowest value and the 10's with the higher value
Using a HashSet is better to know the numbers that you are use. But in your case, I think it's better use a List and remove elements:
var list = new List<int>();
for (int i = 1; i <= 10; i++)
list.Add(i);
// List is 0-index
// list = 1 2 3 4 5 6 7 8 9 10
int rng = random.Next(0, list.Count - 1);
// Suppose rgn=3: You get 3 value and remove it from the list
var value = list[rgn];
list.RemoveAt(rgn);
// list = 1 2 4 5 6 7 8 9 10
// Now you get a value between 0...8 (list.Count is 9)
rng = random.Next(0, list.Count - 1);
// Suppose rgn=3: You get 4 value and remove it from the list
var value = list[rgn];
list.RemoveAt(rgn);
// list = 1 2 5 6 7 8 9 10
// Now you get a value between 0...7 (list.Count is 8)
rng = random.Next(0, list.Count - 1);
// Suppose rgn=5: You get 7 value and remove it from the list
var value = list[rgn];
list.RemoveAt(rgn);
// list = 1 2 5 6 8 9 10
...
When list has one element you don't need use random.
When your list is empty, fill again and repeat the whole process.
In this form you always get an element with each random call. Using HashSet you may try a lot of random calls to get a nonused number.
A class for that maybe:
public class RandomClass
{
private readonly List<int> _list;
private readonly Random _random;
public RandomClass()
{
this._list = new List<int>();
this._random = new Random();
}
private void PopulateList()
{
for (int i = 1; i <= 10; i++)
this._list.Add(i);
}
public int GetNumber()
{
if (this._list.Count == 0)
{
this.PopulateList();
}
if (this._list.Count > 1)
{
int rng = this._random.Next(0, this._list.Count);
var value = this._list[rgn];
this._list.RemoveAt(rgn);
return value;
}
else
{
var value = this._list[0];
this._list.RemoveAt(0);
return value;
}
}
}
UPDATE: Some about List, Arrays and other collections
Array and List are very similar. The main difference is that an array is a continuous block of memory while List (in memory) it's not a block. Array is faster to iterate (address of first element + multiply for sizeof each element) but slower when you want to add/remove elements (you must create other array and copy the elements). From the point of view of an user, both of them are used to store a list of items and iterate them.
Other collections very interesting are HashSet and Dictionary. These collections are sets, you can't access their elements using an index. You saw an example for HashSet in this page: Add a number to the set and query it if you want know if that number appear before. The key with this sets are that you access to their elements using a hash. Instead of an index, you use whatever you want as a key and an algorithm get quickly the position of the element in the set. Dictionary is like a HashSet but you can store addicional data asociated to the key.
In many cases, you'll use both of them: a list to iterate sequencially and a dictionary to direct access to elements. For example, you have a lot of Persons that you show in some order (name, surname...). You store them in a List an allow user to change the order (using Sort of the list). You use a list because you show and use that order many times: you need ordered Persons.
But you have many, many Persons. Suppose that your program allow search Persons by Id and Name. Each time a user search for Persons you must iterate a very long list. It's not efficient. So you define two Dictionary:
Dictionary<int, List<Person>> personsById;
Dictionary<string, List<Person>> personsByName;
Also, you have a List:
List<Person> allPersons;
And we need some operations:
public void AddPerson(Person person)
{
Person existingPerson;
if (personsById.TryGetValue(person.Id, out existingPerson))
{
// Already exists: don't add duplicated persons
return;
}
personsById.Add(person.Id, person);
// Maybe more than one person with the same name. It's the reason why use a List here
List<Person> list;
if (personsByName.TryGetValue(person.Name, out list))
{
// There are other persons with this name, so the list exists. Simply add person to list
list.Add(person);
}
else
{
// Is the first person with this name: create the list and associate to the name
personsByName.Add(person.Name, new List<Person> { person });
}
// Always add to main list
allPersons.Add(person);
}
public void RemovePerson(Person person)
{
if (!personsById.TryGetValue(person.Id, out _))
{
// Not exists: do nothing
return;
}
personsById.Remove(person.Id);
// NOTE: Here we are removing person assuming that you never have different instances
// of person. If you can create different instances for a person, here we must iterate
// the lists to find the person
List<Person> list;
if (personsByName.TryGetValue(person.Name, out list))
{
list.Remove(person);
}
allPersons.Remove(person);
}
public Person GetPerson(int id)
{
return this.personsById.TryGetValue(id, out Person person) ? person : null;
}
public List<Person> GetPersons(string name)
{
return this.personsByName.TryGetValue(name, out List<Person> list) ? list : null;
}
It's a very basic example but I think maybe a good one to learn about this classes.
I have to create a class that keeps tracks of numbers that were already selected in the process of generating a board and selecting numbers during the game.
The 3 classes I need:
1) A "reset" class that initalizses the class once the card is filled with numbers, so that the array can be used again to keep track of the numbers selected during the game
2) A "isNumberUsed" class that is given the random integer and checks whether the random number is in the numbersList array or not
3) A "setUsedNumber" class that adds the unique random number generated to the numbersList array.
I have been working on this and would love any feedback. Thank you!
public class SelectedNumbersListType
{
private int[] numbersList;
private int position;
public SelectedNumbersListType()
{
numbersList = new int[76];
position = 0;
}
public void reset()
{
// position = numbersList[0];
// position++;
for (position = 0; position < numbersList.Length; position++)
{
numbersList[position] = 0;
if (position == numbersList.Length)
{
position = numbersList[0];
}
}
// reset();
}
public bool isNumberUsed(int rn)
{
position = numbersList[0];
position++;
if (numbersList[position] == rn)
{
return true;
}
return false;
}
public bool setUsedNumber(int rn)
{
if (numbersList.Contains(rn))
{
Array.Resize(ref numbersList, numbersList.Length+1);
numbersList[numbersList.Length + 1] = rn;
}
return false;
}
}
}
I think it makes sense to step back here and start from the beginning. As #ThomasWeller points out, object-oriented analysis starts with identifying the nouns in your problem space, and then the verbs that act upon those nouns.
When I look at your bingo problem, I only see one noun, the BingoGame. So, I'm going to have a class BingoGame. From the caller's point of view, there are two main actions (verbs) that act upon that noun: DrawNumber and RestartGame. In addition, I think it's useful to be able to get the list of numbers drawn in the game, both in draw order and in sorted order. As a result, I see two more verbs GetDrawnNumbers and GetDrawnNumbersSorted.
In C-family languages, it always makes more sense to start counting at 0 rather than at 1. So, I'm going to work with numbers in the range 0-74, not 1-75. Whenever I display a number, I'll prepend it with the appropriate letter (one of B, I, N, G, or O) and add one. So, I created a private function to do this: GetBingoNumberFromNumber.
In order to draw a number, I need a source of random-ness. The framework provides one (System.Random) - it's not the best random number generator (don't use it to start a casino), but it's good enough here.
I also need a way to retain what numbers have been drawn (both for display, and to reject any duplicate numbers in a game). I'll keep track of these in a List<int>. Finally, I need to know what the letters are in "BINGO", so I'll keept an array of those letters (I could have treated the string "BINGO" as an array of characters, but I thought an array of characters was more obvious. As a result, my class starts with:
public class BingoGame
{
private readonly List<int> _drawnNumbers = new List<int>();
private readonly Random _random = new Random();
//the indexes for this array are (naturally) 0 through 4
private static readonly char[] BingoChars = {'B', 'I', 'N', 'G', 'O'};
}
Now I need to add functionality. Starting the game simply means taking previously drawn numbers and putting them back in the drum. In our case, it means clearing the list of previously drawn numbers:
public void StartGame()
{
_drawnNumbers.Clear();
}
To draw a number, we'll rely on Random.Next, pulling numbers between 0 and 74. However, we need to take care of the case where a duplicate number is pulled during single game. If that happens, we'll throw away the newly drawn number and get another one. We'll look in the list of previously drawn numbers to decide if a number has been previously drawn:
public string DrawNumber()
{
int nextNum;
do
{
nextNum = _random.Next(0, 75); //this will return a number between 0 & 74
} while (_drawnNumbers.Contains(nextNum));
_drawnNumbers.Add(nextNum);
return GetBingoNumberFromNumber(nextNum);
}
Here's the first time we've had to translate one of our 0-74 numbers to something that makes sense in Bingo. Let's do that function:
private string GetBingoNumberFromNumber(int num)
{
//this will result in a number in the 0-4 range
var bingoIndex = num / 15;
return $"{BingoChars[bingoIndex]}-{num + 1}";
}
It's important to understand integer division when reading that function. Dividing any integer between 0 and 14 by the integer 15 will yield zero. Similarly, any number between 15 and 29 when divided by 15 will yield 1. And so on.
Finally, we need to get the "numbers" for the current game. We'll just return the list of drawn numbers, transformed using GetBingoNumberFromNumber. The easiest way to transform a collection is to use LINQ, so:
public IEnumerable<string> GetDrawnNumbers()
{
return from num in _drawnNumbers
select GetBingoNumberFromNumber(num);
}
And, LINQ is good at sorting, so we'll just return the sorted list in nearly the same way:
public IEnumerable<string> GetDrawnNumbersSorted()
{
return from num in _drawnNumbers
orderby num
select GetBingoNumberFromNumber(num);
}
To test this, I threw together a simple WinForms app with two buttons (StartGameBtn and DrawNumberBtn) and two skinny listboxes (NumbersList and SortedList). After wiring up the Click handlers, it looked like:
public partial class Form1 : Form
{
private readonly BingoGame _game = new BingoGame();
public Form1()
{
InitializeComponent();
_game.StartGame();
}
private void StartGameBtn_Click(object sender, EventArgs e)
{
_game.StartGame();
NumbersList.Items.Clear();
SortedList.Items.Clear();
}
private void DrawNumberBtn_Click(object sender, EventArgs e)
{
_game.DrawNumber();
SetListboxItems(NumbersList, _game.GetDrawnNumbers());
SetListboxItems(SortedList, _game.GetDrawnNumbersSorted());
}
private void SetListboxItems(ListBox listbox, IEnumerable<string> numbers)
{
listbox.Items.Clear();
foreach (var item in numbers)
{
listbox.Items.Add(item);
}
}
}
I have a 2D list which holds sentences and a score generated for that sentence, I need to get the sentence which has the highest score.
So the list is:
("This is sentence one", "302")
("And another sentence", "154")
("Oh and heres another", "528")
The function the list is formed and also where I need to get the sentence with the highest score is this:
protected void buildSummary()
{
scoreCoord2 = -1;
for (int x1 = 0; x1 < results.Length; x1++)
{
SortedList<int, string> paragraphScoreslist = new SortedList<int, string>();
for (int x2 = 0; x2 < results[x1].Length; x2++)
{
scoreCoord2++;
paragraphScoreslist.Add(intersectionSentenceScores[scoreCoord2], results[x1][x2]);
}
int maxValue = paragraphScoreslist.Max(k => k.Key);
//string maxValue = paragraphScoreslist.TryGetValue;
TextboxSummary.Text = maxValue.ToString();
}
}
I'm able to get the highest int value from the sorted list, but don't know how to get the string which is tied to it. I think I need to use TryGetValue but I don't know to use it in a 2D list which in of its self I haven't used before.
If you have control over the array replace it with a SortedList and you can use the SortedList.Max() function without hassle. A sorted list is probably the best take on, as it inherently sorted (which you want), so getting the highest (i.e. Max value) will be faster than an unsorted array, or an unsorted List.
If you don't have control over the data you are receiving, project the data you are getting into a new form (the above SortedList
Going with the example you put up in your post, lets call it "matrix" for simplicity sake:
string[,] matrix =
{
{ "This is sentence one", "302" },
{ "And another sentence", "154" },
{ "Oh and heres another", "528" }
};
Here is the code to put it into a sorted List:
// New instance, pretty simple
SortedList<int, string> list = new SortedList<int, string>();
// Loop through the array and project it into a new form
for(int i = 0; i <= matrix.Length(0); i++) {
list.Add(Convert.ToInt32(matrix[i, 1]), matrix[i, 0]);
}
// Get the max value in the list
var maxValue = list.Max(k => k.Key);
Now you can do what you want with the value. If you want to get the sentence for it you should use the TryGetValue method, but that's up to you. Like this:
string sentence= string.Empty;
if (list.TryGetValue(maxValue, out sentence))
{
// Do something with the string you got
}
For more information how to use the whole Try... methods you should read up on out and ref parameters.
Anything else?
I was wondering how get on with this code, currently working on a tournament bracket system.
Currently I have created a comboBox that fetches all the lines from "log.txt" there are 16 lines in the txt file; then I created a assign button that is supposed to assign all the names into 16 textboxes called User1 --> User16, however the same name cant be repeated.
I looked at "Array of list" & "Array of string", but I seem to be stuck since I cant really figure out what to put in the code.
my random button looks like this at the moment:
private void assign_Click(object sender, EventArgs e)
{
int x;
Random rnd = new Random();
x = rnd.Next(0, 16);
User1.Text = comboBox2.Items[x].ToString();
x = rnd.Next(0, 16);
User2.Text = comboBox2.Items[x].ToString();
x = rnd.Next(0, 16);
User3.Text = comboBox2.Items[x].ToString();
x = rnd.Next(0, 16);
User4.Text = comboBox2.Items[x].ToString();
and so on untill i hit
x = rnd.Next(0, 16);
User16.Text = comboBox2.Items[x].ToString();
}
One of the simplest, but not necessarily most efficient, way to do this is to put all your strings into a List<string> and remove them randomly one-by-one. This would work a lot better if you put all your textboxes into a collection as well. For example, given a list of strings called myStrings and a collection of textboxes called myTextboxes, you could:
for (var i=0; i < myStrings.Count; i++)
{
var idx = rnd.Next(0, myStrings.Count);
myTextboxes[i].Text = myStrings[idx]; // Note: we are assuming the two collections have
// the same length
myStrings.RemoveAt(idx);
}
This is very easy to implement and very easy to get right, but it's not terribly efficient (for 16 items, it probably doesn't matter) because your collection is repeatedly resized. For a more efficient approach, first shuffle your strings using the Fisher-Yates shuffle and then just assign the first entry from your shuffled strings to the first textbox, the second to the second, and so on.
You could use a List, and after each assignment you could remove the assigned item from the list. This would prevent duplicates.
http://msdn.microsoft.com/en-us/library/cd666k3e(v=vs.110).aspx
How about removing each item after selecting it?
Try something like
comboBox1.Items.RemoveAt(x);
After adding it and each time your
x = rnd.Next(0, 16);
code will reduce to
x = rnd.Next(0, 15);
until it reaches zero.
A different approach would be after selecting one randomly loop through all the filled ones (or all in general for simpler code) and check if it is already selected. If already selected get a new one until it's different.
For that you could use an array of textboxes (store what you have in an array) and loop through them like so
for(int i=0;i<16;i++)
if(textBoxArray[i].Text==comboBox2.Items[x].toString()){
chosen=true;
}
But removing them from the combobox is much simpler and much faster as code. If you want them to still appear in your combobox you could simultaneously in a List, get your items from that List and remove it from there.
The user will not see anything.
To accomplish this, is fairly simple.
First, you know there are 16 items in total. You don't need to randomize the list but rather, randomize the index that you use to access the item of the list. This part you know.
In order to avoid repeating items, you need to keep a list of indexes that have already been used. Once you have determined an unused index, that's when you need to access your list.
Example:
class Sample
{
List<int> _usedIndexes;
public Sample()
{
_usedIndexes = new List<int>();
}
public int GetRandomIndex(int s, e)
{
Random rnd = new Random();
//Initialize with a random number
int x = rnd.Next(s, e);
//While the index exists in the list of used indexes, get another random number.
while(_usedIndexes.Exists(index => index == x))
{
x = rnd.Next(s, e);
}
//Add the number to the list of used indexes
_usedIndexes.Add(x);
return x;
}
}
Then you simply access the List of names you have with the index you have acquired as follows:
int unusedIndex = GetRandomIndex(0, 16);
User1.Text = comboBox2.Items[unusedIndex].ToString();
I'm a C# newbie and I'm really confused about something I'm trying to do for a project in a C# class.
The assignment is some list manipulation in C#.
The program accepts a list of items in the text box, then iterates through those items, creating multiple copies of the list. It randomly resizes each copy of the list to between 3 and all items. It then outputs all the copies.
The problem I'm having is that when I step through this program with the debugger, I get the expected output. The same happens if I display a message box after each iteration (as I have in the code below).
However, if I just run the program straight through, I get a different output. Instead of variations in the lists, all the copies of the list are exactly the same.
If you see in the code I've commented "// FIRST DEBUG MESSAGEBOX" and "// SECOND DEBUG MESSAGEBOX". If the first debug messagebox code is left in there, the output is as expected...multiple versions of the list are output with random lengths between 3 and all items.
However, and this is where I'm confused...if you comment out the first debug messagebox code, you get a different result. All versions of the list output are the same length with no variation.
Any help would be appreciated! Here's the code I have so far...sorry if it's terrible - I'm new at C#:
public partial class MainForm : Form
{
/**
* Vars to hold raw text list items
* and list items split by line
*/
String rawListItems = "";
List<string> listItems = new List<string>();
List<List<string>> textListItems = new List<List<string>>();
public MainForm()
{
InitializeComponent();
}
private void cmdGo_Click(object sender, EventArgs e)
{
// store the contents of the list item text box
this.rawListItems = txtListItems.Text;
this.listItems.AddRange(Regex.Split(this.rawListItems, "\r\n"));
// setup min and max items - max items all items
int minItems = 3;
int maxItems = this.listItems.Count;
// We'll copy this list X times, X = same number of items in list
for (int i = 0; i < this.listItems.Count; i++)
{
// make a copy of the list items
List<string> listItemsCopy = new List<string>(this.listItems);
// get a random number between min items and max items
Random random = new Random();
int maxIndex = random.Next(minItems, maxItems + 1); // max is exclusive, hence the +1
// remove all elements after the maxIndex
for (int j = 0; j < listItemsCopy.Count; j++)
{
if (j > maxIndex)
{
listItemsCopy.RemoveAt(j);
}
}
// add the list copy to the master list
this.textListItems.Add(listItemsCopy);
// FIRST DEBUG MESSAGEBOX
String tst = "";
foreach (string item in listItemsCopy)
{
tst += item + " ## ";
}
MessageBox.Show(tst);
}
// SECOND DEBUG MESSAGEBOX
String output = "";
foreach (List<string> listitem in this.textListItems)
{
foreach (string item in listitem)
{
output += item + " ## ";
}
}
MessageBox.Show(output);
}
}
Move the creation of Random out of the loop:
Random random = new Random();
By default, the constructor uses a default time based seed. In a tight loop, you may be getting 'the same' random generator instead of a different one with each loop.
When using MessageBoxes or single stepping, you are allowing the timer to run and getting 'a new' random generator in each loop.
I don't understand your assignment exactly, but this loop seems to be incorrect:
for (int j = 0; j < listItemsCopy.Count; j++)
{
if (j > maxIndex)
{
listItemsCopy.RemoveAt(j);
}
}
when you remove an element in the middle of a list, elements after that get shifted, so not all the elements after maxIndex get removed, as you might expect.
In circumstances where stepping through the code in a debugger affects the behaviour of the program, a useful alternative debugging technique is to use the System.Diagnostics namespace in particular the Trace class.
The Trace functions work much like Console.WriteLine(), you can trace a string or a format string plus an array of objects to populate the format string, e.g.:
Trace.TraceInformation("some message that tells me something");
Trace.TraceInformation("some useful format string {1}, {0}",
new object[] {someObject, someOtherObject});