C# - Struct Improvements in C# 10.0
Keyur Ramoliya
Posted on December 2, 2023
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:
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.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})");
}
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.
Posted on December 2, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.