Results for tag "c-randomization"

Random String / Integer erzeugen

Auch diesmal nur ein kurzes Codesnippet, welches ich gerade beruflich im Einsatz hatte:

[sourcecode language=“csharp“]
/// <summary>
/// Gets a random integer value.
/// </summary>
/// <param name="intMin">The int min.</param>
/// <param name="intMax">The int max.</param>
/// <returns></returns>
public static int GetRandomInteger(int intMin, int intMax)
{
//Create a new instance of the class Random
Random randomNumber = new Random();
//Generate a random number using intMin as the minimum and intMax as the maximum
int i = randomNumber.Next(intMin, intMax);

// destroying the object is neessary, otherwise if calling the GetRandomInteger function
// several times you will always get the same result!!!
randomNumber = null;
return i;
}

/// <summary>
/// Gets the random string.
/// </summary>
/// <param name="intLenghtOfString">The int lenght of string.</param>
/// <returns></returns>
public static string GetRandomString(int intLenghtOfString)
{
//Create a new StrinBuilder that would hold the random string.
StringBuilder randomString = new StringBuilder();
//Create a new instance of the class Random
Random randomNumber = new Random();
//Create a variable to hold the generated charater.
//Create a loop that would iterate from 0 to the specified value of intLenghtOfString
for (int i = 0; i <= intLenghtOfString; ++i)
{
//Generate the char and assign it to appendedChar
Char appendedChar = Convert.ToChar(Convert.ToInt32(26 * randomNumber.NextDouble()) + 65);
//Append appendedChar to randomString
randomString.Append(appendedChar);
}
//Convert randomString to String and return the result.
return randomString.ToString();
}
[/sourcecode]

Chris aka. schönes Wochenende!