Essential Features of C# 12 You Need to Know

Introduction

Hey everyone, excited about writing some C# code? Guess what? Version 12 is here, and it's got some awesome new tricks up its sleeve! Forget long, messy code or struggling to create collections – C# 12 makes things simpler and way cooler.

Picture this: no more separate constructor methods, just write them right inside the class! Collections like lists and arrays? Bam, create them in a snap with a brand new shortcut. Want to use arrays right where you need them? Easy peasy, inline arrays are here to save the day. And wait, there's more! Lambdas got an upgrade, too, handling asynchronous tasks and passing variables like a pro.

So, are you ready to unleash the power of C# 12? Buckle up. We're diving deep into these features and showing you how to write cleaner, faster, and just plain awesome code. Let's make coding fun again! 

1. Primary Constructors

C# 12 simplifies object creation by allowing constructors directly within the class/struct definition alongside the properties and methods. This eliminates the need for separate constructor methods, boosting code conciseness and readability.

Benefits

  • Conciseness: No need for repetitive constructor methods, streamlining code, and improving readability.
  • Accessibility: Constructor logic is readily available within the class definition, facilitate understanding and maintenance.
  • Readability: Code clearly reflects the object's structure and initialization requirements.

Example

public class Person(string firstName, string lastName)
{
    public string FullName => $"{firstName} {lastName}";
}

Here, the constructor takes firstName and lastName parameters and defines a FullName property for easy access. Creating a Person object is as simple as:

Person johnDoe = new Person("John", "Doe");

2. Collection Expressions

This feature introduces a streamlined syntax for creating common collections like arrays, lists, and spans.
Forget verbose initializers with nested brackets and commas! Now, use a concise format directly within your code.

Benefits

  • Readability: Code becomes cleaner and easier to understand, promoting maintainability.
  • Efficiency: Less boilerplate code reduces typing and potential errors.
  • Expressiveness: Directly embed the collection within expressions for greater flexibility.

Example

Instead of this traditional approach:

int[] numbers = new int[] { 1, 2, 3, 4, 5 };
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };

Use the collection expression syntax:

int[] numbers = [1, 2, 3, 4, 5];
List<string> names = ["Alice", "Bob", "Charlie"];

This reduces clutter and makes your code more expressive.

3. Inline Arrays

C# 12 brings further convenience with inline arrays, allowing you to initialize arrays directly within expressions. This cuts down on redundant variable declarations and promotes concise, memory-efficient code.

Benefits

  • Memory efficiency: Avoids unnecessary variable creation and allocation, reducing memory overhead.
  • Conciseness: Write compact and expressive code by directly injecting the array within expressions.
  • Readability: Improves code clarity by eliminating temporary variables and focusing on the core logic.

Example

This traditional approach uses a temporary variable:

int sum = 0;
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
    sum += numbers[i];
}

With inline arrays, the code becomes:

int sum = Array.Sum([1, 2, 3, 4, 5]);

This eliminates the numbers variable and directly uses the inline array within the Array.Sum call.

4. Expanded Parameterless Struct Constructors

C# 12 gives you more control over struct initialization by allowing parameterless constructors alongside primary constructors. This caters to scenarios where optional initialization or default values are desired.

Benefits

  • Optional initialization: Enables creating structs without explicitly providing values for all fields.
  • Default values: Define specific default values for fields when no arguments are provided to the constructor.
  • Flexibility: Cater to different scenarios where both parameterless and parameter-based initialization are desired.

Example

public struct Point
{
    public int X, Y;
    public Point(int x, int y) { X = x; Y = y; } // Primary constructor
    public Point() : this(0, 0) {} // Parameterless constructor with default values
}

Now, you can create Point objects with or without explicitly setting the X and Y values.

5. Enhanced Lambda Expressions

C# 12 takes lambdas to the next level with several enhancements:

  • Explicit this for instance members: Ensures clarity and prevents accidental access to static members when using lambdas with instance methods.
  • await in async lambdas: Enables asynchronous operations directly within lambda expressions, simplifying event handlers and other scenarios.
  • ref and out parameters: Allows lambdas to modify variables passed by reference, opening up new possibilities for efficient data manipulation.

Conclusion

C# 12 isn't just an update, it's a superpower for your code! Forget long, messy instructions – these new features make coding easier, faster, and way more fun. Build objects in a snap, create collections like magic, and bend lambdas to your will. No more code spaghetti, just clean, readable masterpieces. So, grab your coding tools, explore these features, and watch your skills skyrocket! C# 12 is here, and it's time to write like a pro!

You can try these features using the latest Visual Studio 2022 version or the .NET 8 SDK

I hope you will find this article helpful. If you have any suggestions, then please feel free to ask in the comment section.

Thank you.


Similar Articles