C# || How To Generate A Random String Of A Specified Length Using C#
The following is a module with functions which demonstrates how to generate a random code of a specified length using C#.
The function demonstrated on this page has the ability to generate random strings that contains only letters, only numerical digits, or alphanumeric strings.
1. Random Code – Alphabetical
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that contains only letters.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Alphabetical // Generate code containing only letters var letters = Utils.Code.GetRandom(5); // Display the code Console.WriteLine($"Code: {letters}"); // example output: /* Code: PBduQ */ |
2. Random Code – Numeric
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that contains only digits.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Numeric // Generate code containing only digits var numeric = Utils.Code.GetRandom(7, Utils.Code.Type.Numeric); // Display the code Console.WriteLine($"Code: {numeric}"); // example output: /* Code: 1768033 */ |
3. Random Code – Alphanumeric
The example below demonstrates the use of ‘Utils.Code.GetRandom‘ to generate a code of a specified length that is alphanumeric.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Random Code - Alphanumeric // Generate alphanumeric code var alphaNumeric = Utils.Code.GetRandom(10, Utils.Code.Type.AlphaNumeric); // Display the code Console.WriteLine($"Code: {alphaNumeric}"); // example output: /* Code: iSL3bwu09O */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Code { public enum Type { /// <summary> /// Code contains only letters /// </summary> Alphabetical, /// <summary> /// Code contains only digits /// </summary> Numeric, /// <summary> /// Code contains letters and digits /// </summary> AlphaNumeric } /// <summary> /// Generates a random string of a specified length according to the type /// </summary> /// <param name="length">The length of the random string</param> /// <param name="type">The type of string to generate</param> /// <returns>The random string according to the type</returns> public static string GetRandom(int length , Code.Type type = Code.Type.Alphabetical) { var digits = "0123456789"; var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var source = string.Empty; switch (type) { case Code.Type.Alphabetical: source = alphabet; break; case Code.Type.Numeric: source = digits; break; case Code.Type.AlphaNumeric: source = alphabet + digits; break; default: throw new ArgumentException($"Unknown type: {type}", nameof(type)); } var r = new Random(); var result = new System.Text.StringBuilder(); while (result.Length < length) { result.Append(source[r.Next(0, source.Length)]); } return result.ToString(); } } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 14, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Generate code containing only letters var letters = Utils.Code.GetRandom(5); // Display the code Display($"Code: {letters}"); Display(""); // Generate code containing only digits var numeric = Utils.Code.GetRandom(7, Utils.Code.Type.Numeric); // Display the code Display($"Code: {numeric}"); Display(""); // Generate alphanumeric code var alphaNumeric = Utils.Code.GetRandom(10, Utils.Code.Type.AlphaNumeric); // Display the code Display($"Code: {alphaNumeric}"); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply