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:
Comments
Post a Comment