C# — Generate a Random String in One Line

 

C# — Generate a Random String in One Line

Most people use loops to build random strings, but here’s a fun way with LINQ:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // Generate a random 12-character string (letters + digits) in one line
        string randomCode = new string(
            Enumerable.Range(0, 12)
                      .Select(_ => "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[new Random().Next(36)])
                      .ToArray()
        );

        Console.WriteLine($"Your unique code: {randomCode}");
    }
}


What’s cool about it?

  • Uses LINQ and Enumerable.Range instead of loops.

  • Builds the string in a functional style.

  • The source alphabet can be changed to include symbols, lowercase, etc.

🧩 Curiosity twist: You can even generate a “random word” from emojis instead of letters:

string emojiWord = new string( Enumerable.Range(0, 5) .Select(_ => "🍕🍔🍟🍣🍩🍪🍫🍿🥑"[new Random().Next(9)]) .ToArray() ); Console.WriteLine($"Emoji word: {emojiWord}");

Comments

Popular posts from this blog

About Me

3. C# — Get Unique Characters in One Line