5 Curious C# Tricks You Might Not Know

 As developers, we often use C# in very structured and predictable ways. But sometimes the language has neat shortcuts and hidden gems that can make even simple tasks more elegant (or just more fun!). In this post, I’ll share a handful of curious C# tricks—small snippets that do something simple but in a unique way. These are not necessarily for production code (though some are handy!), but they’ll make you see C# a little differently.


1. Reverse a String with LINQ

Most people use loops or Array.Reverse—but here’s a LINQ way:

string text = "Hello World"; string reversed = new string(text.Reverse().ToArray()); Console.WriteLine(reversed); // dlroW olleH

Why it’s cool: clean, expressive, and just one line.


2. Swap Two Numbers Without a Temp Variable

Old school swaps usually need a temporary variable, but C# tuples make it elegant:

int a = 5, b = 10; (a, b) = (b, a); Console.WriteLine($"a = {a}, b = {b}"); // a = 10, b = 5

Why it’s cool: leverages C# tuple assignment.


3. Palindrome Check in One Line

Checking if a number (or string) is a palindrome doesn’t need a loop:

int num = 12321; bool isPalindrome = num.ToString().SequenceEqual(num.ToString().Reverse()); Console.WriteLine(isPalindrome); // True

Why it’s cool: makes palindrome checks ridiculously short.


4. Day of the Week in Emoji

Turn boring dates into fun outputs with emojis:

string[] days = { "🌞", "🌕", "🔥", "🌊", "🌳", "⭐", "🎉" }; string todayEmoji = days[(int)DateTime.Now.DayOfWeek]; Console.WriteLine($"Today is {todayEmoji}");

Why it’s cool: adds a playful twist to console apps.


5. FizzBuzz in a LINQ One-Liner

FizzBuzz is a classic interview problem. Here’s a LINQ twist:

Enumerable.Range(1, 20).ToList() .ForEach(i => Console.WriteLine( (i % 3 == 0, i % 5 == 0) switch { (true, false) => "Fizz", (false, true) => "Buzz", (true, true) => "FizzBuzz", _ => i.ToString() }));

Why it’s cool: functional, concise, and nerd-approved.


Wrapping Up

These little tricks show how expressive and playful C# can be. While some are just fun party tricks (looking at you, emoji days 😅), others—like tuple swaps and LINQ-based checks—can genuinely make your code cleaner.

👉 Try them out, and next time you write C#, maybe you’ll surprise yourself with how creative the language can be.

Comments

Popular posts from this blog

About Me

3. C# — Get Unique Characters in One Line

C# — Generate a Random String in One Line