C# - Struct Improvements in C# 10.0

theramoliya

Keyur Ramoliya

Posted on December 2, 2023

C# - Struct Improvements in C# 10.0

C# 10.0 brought several improvements to structs, enhancing their functionality and making them more flexible for various use cases. One significant enhancement is the ability to declare parameterless constructors and field initializers in structs.

Here's how to utilize these struct improvements:

  1. Parameterless Constructors in Structs:
    You can now define a parameterless constructor in a struct. This allows for more control over how struct instances are initialized, especially when used with collections or serialization frameworks.

  2. Field Initializers in Structs:
    Similar to classes, C# 10.0 structures allow field initializers. This means you can assign default values to fields directly in their declaration.

Example:

public struct Point
{
    public double X { get; set; }
    public double Y { get; set; }

    // Parameterless constructor
    public Point()
    {
        X = 0;
        Y = 0;
    }

    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public static void Main()
{
    var defaultPoint = new Point(); // Calls parameterless constructor
    var customPoint = new Point(5.0, 10.0);

    Console.WriteLine($"Default Point: ({defaultPoint.X}, {defaultPoint.Y})");
    Console.WriteLine($"Custom Point: ({customPoint.X}, {customPoint.Y})");
}
Enter fullscreen mode Exit fullscreen mode

In this example, the Point struct includes a parameterless constructor, allowing you to create a Point with default values without having to provide specific arguments. This makes structs more versatile and user-friendly, especially when you need to ensure a certain state upon initialization.

These improvements make structs more like classes in terms of their capabilities, offering more flexibility in designing your data structures while still allowing you to benefit from the value-type semantics of structs.

💖 💪 🙅 🚩
theramoliya
Keyur Ramoliya

Posted on December 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

C# - Struct Improvements in C# 10.0
csharp C# - Struct Improvements in C# 10.0

December 2, 2023

C# - File-scoped Namespaces
csharp C# - File-scoped Namespaces

December 1, 2023

C# - with expressions
csharp C# - with expressions

December 21, 2023