C# Tips and Tricks #11 – Generate random alphanumeric string

There are times when the developers would encounter scenarios where they need to generate a random alphanumeric string to be used with in their application.

How to generate random alphanumeric string in C# ?

Here’s a sample code snippet demonstrating how to do it using LINQ Query in C#.

using System;
using System.Linq;
namespace ConsoleApp1
{
    class Program
    {
        private static Random random = new Random();
        static void Main(string[] args)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var result = (from m in Enumerable.Repeat(chars, 10)
                          select m[random.Next(m.Length)]).ToArray();
            string resultStr = new string(result);
            Console.WriteLine(resultStr);

            Console.ReadLine();
        }
   
}
}
   

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...