What is Collection Expressions in C# 12?

Introduction

C# 12 comes to the rescue with collection expressions, a magical new feature that lets you build collections with conciseness and a dash of fun! Think of them as superpowers for crafting your beloved lists, arrays, and even those sneaky spans. Let's explore how they work their magic, even if you're just starting out with C#.

Imagine this. you're building a playlist for your next road trip. Instead of long lines of code adding each song, you can whip up your playlist in one line using a collection expression.

var roadTripPlaylist = ["Highway to Hell", "Dancing Queen", "Mr. Blue Sky", "Bohemian Rhapsody"];

Boom! Your playlist is ready to fuel your adventure. Here's how collection expressions work their magic.

1. Creating Collections in a Flash

  • Arrays: [1, 2, 3] creates an array of numbers in a snap.
  • Lists: ["apple", "banana", "cherry"] conjures up a list of fruits just like that.
  • Spans: ["a", "b", "c", "d"] magically creates a span of letters to play with.

2. Spreading

  • Combine multiple collections with the spread operator (...).
    var partyMix = [roadTripPlaylist..., chillVibesSongs];
    

3. Customizing Your Creations

  • Use initializers for even more control.
    var shoppingList = new List<string> { "milk", "eggs", "bread" }; // List with items pre-selected
    var movieNight = new string[] { "comedy", "horror", "animation" }; // Array with genres ready to roll
    

4. Friendly with Familiar Faces

  • Collection expressions work seamlessly with the existing initializer syntax you already know.
var schoolSupplies = new List<string> { "pencils", "notebooks", "backpack" };

Benefits of Collection Expression

  • Readability: No more confusing code; your collections are clear and easy to understand.
  • Efficiency: These expressions can sometimes boost performance.
  • Consistency: One powerful syntax for all your collection needs.

Real-World Examples

  • Building a recipe app? Define ingredient lists with ease.
    var pancakeRecipe = ["flour", "milk", "eggs", "butter"];
    
  • Creating a to-do list? Organize your tasks with a single line.
    var dailyTasks = ["finish report", "clean apartment", "call mom"];
    

Conclusion

Collection expressions are game-changers for beginners and seasoned developers alike. They simplify collection creation, enhance code readability, and make your C# projects sparkle with elegance. So, embrace their power, unleash your creativity, and watch your collections come alive – whether it's a rocking playlist, a delicious recipe, or a conquered to-do list. C# 12 and collection expressions have your back!


Recommended Free Ebook
Similar Articles