Getting started with C# LanguageVerbatim StringsOperatorsExtension MethodsCollection InitializersString InterpolationC# 6.0 FeaturesConstructors and FinalizersKeywordsGenericsReflectionInheritanceNull-Coalescing OperatorUsing StatementString Escape SequencesException HandlingNull-conditional OperatorsBuilt-in TypesLambda expressionsAsync-AwaitPropertiesThreadingUsing DirectiveMethodsYield KeywordEventsLINQ QueriesCommon String OperationsExpression TreesOverload ResolutionString.Formatnameof OperatorUnsafe Code in .NETInitializing PropertiesBindingList<T>ILGeneratorObject initializersXML Documentation CommentsPreprocessor directivesDynamic typeAnonymous typesStructsTuplesEnumAccess ModifiersTask Parallel LibraryAttributesGuidSingleton ImplementationDelegatesNullable typesGarbage Collector in .NetNetworkingArraysEquality OperatorLock StatementAction FiltersXmlDocument and the System.Xml namespaceDateTime MethodsBackgroundWorkerPolymorphismStatic ClassesIndexerIDisposable interfaceAliases of built-in typesImmutabilityXDocument and the System.Xml.Linq namespaceC# 7.0 FeaturesPerforming HTTP requestsGenerating Random Numbers in C#LoopingNamed ArgumentsDiagnosticsInterfacesIEnumerableNaming ConventionsAn overview of c# collectionsChecked and UncheckedRecursionFunctional ProgrammingLiteralsCastingNullReferenceExceptionFunc delegatesLINQ to XMLHash FunctionsHandling FormatException when converting string to other typesCryptography (System.Security.Cryptography)INotifyPropertyChanged interfaceValue type vs Reference typeC# 4.0 FeaturesIQueryable interfaceTask Parallel Library (TPL) Dataflow ConstructsStreamRuntime CompileConditional StatementsInteroperabilityOverflowEquals and GetHashCodeType ConversionParallel LINQ (PLINQ)String ManipulationString ConcatenatePartial class and methodsStopwatchesRegex ParsingC# ScriptC# 3.0 FeaturesAsync/await, Backgroundworker, Task and Thread ExamplesTimersFunction with multiple return valuesBinary SerializationMaking a variable thread safeIComparableCode ContractsIteratorsAssemblyInfo.cs ExamplesFile and Stream I/OCode Contracts and AssertionsCachingC# 5.0 FeaturesImplementing Flyweight Design PatternStringBuilderImplementing Decorator Design PatternAccessing DatabasesT4 Code GenerationMicrosoft.Exchange.WebServices.NET Compiler Platform (Roslyn)Data AnnotationUsing SQLite in C#System.Management.AutomationFileSystemWatcherSystem.DirectoryServices.Protocols.LdapConnectionNamed and Optional ArgumentsComments and regionsC# Authentication handlerPointers & Unsafe CodePointersHow to use C# Structs to create a Union type (Similar to C Unions)BigIntegerDependency InjectionReactive Extensions (Rx)Creational Design PatternsCreating a Console Application using a Plain-Text Editor and the C# Compiler (csc.exe)Reading and writing .zip filesGeneric Lambda Query BuilderImport Google ContactsLambda ExpressionsCLSCompliantAttributeObservableCollection<T>Synchronization Context in Async-AwaitICloneableRead & Understand StacktracesLinq to ObjectsASP.NET IdentityAccess network shared folder with username and passwordAsynchronous SocketStructural Design PatternsO(n) Algorithm for circular rotation of an arrayCreating Own MessageBox in Windows Form ApplicationIncluding Font ResourcesObject Oriented Programming In C#Using json.netGetting Started: Json with C#Windows Communication Foundation

Generating Random Numbers in C#

Other topics

Remarks:

The random seed generated by the system isn't the same in every different run.

Seeds generated in the same time might be the same.

Generate a random int

This example generates random values between 0 and 2147483647.

Random rnd = new Random();
int randomNumber = rnd.Next();

Generate a Random double

Generate a random number between 0 and 1.0. (not including 1.0)

Random rnd = new Random();
var randomDouble = rnd.NextDouble();

Generate a random int in a given range

Generate a random number between minValue and maxValue - 1.

Random rnd = new Random();
var randomBetween10And20 = rnd.Next(10, 20);

Generating the same sequence of random numbers over and over again

When creating Random instances with the same seed, the same numbers will be generated.

int seed = 5;
for (int i = 0; i < 2; i++)
{
   Console.WriteLine("Random instance " + i);
   Random rnd = new Random(seed);
   for (int j = 0; j < 5; j++)
   {
      Console.Write(rnd.Next());
      Console.Write(" ");
   }

   Console.WriteLine();
}

Output:

Random instance 0
726643700 610783965 564707973 1342984399 995276750
Random instance 1
726643700 610783965 564707973 1342984399 995276750

Create multiple random class with different seeds simultaneously

Two Random class created at the same time will have the same seed value.

Using System.Guid.NewGuid().GetHashCode() can get a different seed even in the same time.

Random rnd1 = new Random();
Random rnd2 = new Random();
Console.WriteLine("First 5 random number in rnd1");
for (int i = 0; i < 5; i++)
    Console.WriteLine(rnd1.Next());

Console.WriteLine("First 5 random number in rnd2");
for (int i = 0; i < 5; i++)
    Console.WriteLine(rnd2.Next());

rnd1 = new Random(Guid.NewGuid().GetHashCode());
rnd2 = new Random(Guid.NewGuid().GetHashCode());
Console.WriteLine("First 5 random number in rnd1 using Guid");
for (int i = 0; i < 5; i++)
    Console.WriteLine(rnd1.Next());
Console.WriteLine("First 5 random number in rnd2 using Guid");
for (int i = 0; i < 5; i++)
    Console.WriteLine(rnd2.Next());

Another way to achieve different seeds is to use another Random instance to retrieve the seed values.

Random rndSeeds = new Random();
Random rnd1 = new Random(rndSeeds.Next());
Random rnd2 = new Random(rndSeeds.Next());

This also makes it possible to control the result of all the Random instances by setting only the seed value for the rndSeeds. All the other instances will be deterministically derived from that single seed value.

Generate a random character

Generate a random letter between a and z by using the Next() overload for a given range of numbers, then converting the resulting int to a char

Random rnd = new Random();
char randomChar = (char)rnd.Next('a','z'); 
//'a' and 'z' are interpreted as ints for parameters for Next()

Generate a number that is a percentage of a max value

A common need for random numbers it to generate a number that is X% of some max value. this can be done by treating the result of NextDouble() as a percentage:

var rnd = new Random();
var maxValue = 5000;
var percentage = rnd.NextDouble();
var result = maxValue * percentage; 
//suppose NextDouble() returns .65, result will hold 65% of 5000: 3250.

Syntax:

  • Random()

  • Random(int Seed)

  • int Next()

  • int Next(int maxValue)

  • int Next(int minValue, int maxValue)

Parameters:

ParametersDetails
SeedA value for generating random numbers. If not set, the default value is determined by the current system time.
minValueGenerated numbers won't be smaller than this value. If not set, the default value is 0.
maxValueGenerated numbers will be smaller than this value. If not set, the default value is Int32.MaxValue.
return valueReturns a number with random value.

Contributors

Topic Id: 1975

Example Ids: 6464,6465,6466,6467,6468,28125,30435

This site is not affiliated with any of the contributors.