How to flip a coin in C# or VB.NET

To flip a coin in C# or VB.NET you just need to use this extension method on a instance of random.

Extension Method C#

public static bool FlipCoin(this Random rand)
{
    return rand.Next(2) == 0;
}

Extension Method VB.NET

<System.Runtime.CompilerServices.Extension> _
Public Shared Function FlipCoin(rand As Random) As Boolean
	Return rand.Next(2) = 0
End Function

generate random numbers in csharp or vb.net

To generate random numbers in csharp or vb.net you simply need to use the Random class which is located in the namespace System.

c# example

var rand = new Random();
int randInt1 = rand.Next(1, 10);
int randInt2 = rand.Next(10); 

vb.net example

Dim rand = New Random()
Dim randInt1 As Integer = rand.Next(1, 10)
Dim randInt2 As Integer = rand.Next(10)

remember that the first rand.Next statements will return a number between 1 and 9 while the second rand.Next statement will return a number between 0 and 9.

 

Tip

If you do new Random() in a Loop the Random is initialised again and again, your Random function can then possibly return the same number several times.
You should keep a single Random instance and keep using Next on it without reinitialising.