Languages
[Edit]
EN

C# / .NET - generate random string of size n characters

0 points
Created by:
Wade
562

In this article, we would like to show you how to generate random string of size n characters in C#.

Quick solution:

string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    "abcdefghijklmnopqrstuvwxyz" +
    "0123456789";

int length = 10;

Random random = new Random();

var result = Enumerable.Repeat(ALPHABET, length)
.Select(s => s[random.Next(s.Length)]).ToArray();

Console.WriteLine(result); // Example output: gDoJlEYyZr

 

Practical example

The following example presents how to generate random string of size n=10 using characters taken from ALPHABET variable.

using System;
using System.Linq;

public class TestClass
{
    public static void Main()
    {
        string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
            "abcdefghijklmnopqrstuvwxyz" +
            "0123456789";

        int length = 10;

        Random random = new Random();

        var result = Enumerable.Repeat(ALPHABET, length)
        .Select(s => s[random.Next(s.Length)]).ToArray();

        Console.WriteLine(result);
    }
}

Example output:

8NyDdsC233

References

  1. Enumerable Class (System.Linq) | Microsoft Docs
  2. Enumerable.Select Method (System.Linq) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join