The release candidate for .NET 7 has already been released. With .NET 7, there is going to be newer version of C# too. Since past few days, I have been trying to learn what are new features available in C# 11. I already have discussed about raw string literals, List Patterns, Generic Attributes in last few articles.
In this short article, we are going to have a look at another new feature from C# 11.
What was previous behavior ?
A struct share all the capabilities of a class type. As in
class type, we can declare fields in the
struct type. Prior to
C# 11, it was mandatory to explicitly initialize all the fields inside the constructor, (only if a constructor is declared in the struct).
The code example given below shows a struct, which has some fields declared. But because they are not initialized, there is a compilation error.
If we just remove the constructor from the Point struct, the error goes away (Comment and let me know why ?).
What is the new behavior ?
Obviously, as the previous compilation error suggested, we can change the language version to preview – or change target framework to
.NET 7. This will mean that we are using
C# 11 will then auto default all those fields, meaning default value of the respective type would be assigned to the fields, without explicitly specifying it in the code.
Where this feature is going to help ?
class types are preferred over
structs. I personally have not worked on applications where structs were being used heavily.
Sometimes, while interacting with third party APIs, or for calling low level APIs from the operating systems, sometimes, structures are preferred. For such applications, the feature is going to help reduce some trivial code.
Do you share the same opinion?
Are you aware of any other type of applications which may get benefited from the feature ?
Let me know your thoughts.