Home
Search
Random Lowercase LetterGenerate a random stream of lowercase letters with the Random Next method.
C#
This page was last reviewed on Sep 14, 2022.
Random lowercase letter. In a C# program, a random lowercase letter is needed. It must be between "a" and "z" inclusive. We can get this letter with a special method.
Method info. We generate random characters by providing inclusive and exclusive bounds to the Random variable. We can then convert the numbers returned to characters.
Random
Char
Example code. The RandomLetter class is a static class, meaning it cannot be instantiated. GetLetter provides a way to get the next random letter.
Info The GetLetter method provides a way to get another random letter. It internally references the static field Random variable.
And It calls the Next method and stores the result of that onto the evaluation stack as an integer local variable.
Then It uses type conversion to convert the value of "0-25" to the letters "a-z."
Casts
using System; static class RandomLetter { static Random _random = new Random(); public static char GetLetter() { // This method returns a random lowercase letter. // ... Between 'a' and 'z' inclusive. int num = _random.Next(0, 26); // Zero to 25 char let = (char)('a' + num); return let; } } class Program { static void Main() { // Get random lowercase letters. Console.WriteLine(RandomLetter.GetLetter()); Console.WriteLine(RandomLetter.GetLetter()); Console.WriteLine(RandomLetter.GetLetter()); Console.WriteLine(RandomLetter.GetLetter()); Console.WriteLine(RandomLetter.GetLetter()); } }
i q f t o
Random fields. When using Random, it is often useful to store the Random variable itself as a static field. Random implements a stream of randomness.
Static
A summary. We examined a program that implements a random letter generation routine. The method shown returns a random letter between "a" and "z" in char representation.
Final notes. The method can be called sequentially—it is a random stream. The static modifier is used here to simplify the program layout and reduce instantiations.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2022 (grammar).
Home
Changes
© 2007-2022 Sam Allen.