Capacity was previously restricted to the use of Records with C# 12. We can now also use Primary Constructors in the class implementation and structs. Parameters can be defined in the declaration of a class or struct, making it possible to use them in the body of these structures.
In the next listing, we have an example of this type of implementation with the Projeto class:
-> The Primary Constructor parameters accompany the declaration of the Projeto class name (line 3);
-> The TargetFramework, Descricao, and Tecnologias properties are read-only, receiving the parameters specified via Primary Constructor;
-> A simple constructor can reference the Primary Constructor, as indicated in lines 5 and 6;
-> HorasTrabalhadas follows the behavior of a conventional property, allowing the reading and writing of values.
At the time of this article’s publication, Primary Constructors in classes and structs are still considered a feature in Preview mode. Thus, it becomes necessary to configure the LangVersion attribute in the .csproj file of projects that use this capability with the preview value:
In the next listing, we have examples of using the Primary Constructor of the Projeto type, as well as the conventional constructor that references this element:
When running this application, the result shown in the following image will be produced:
This first project has been made available on GitHub:
https://github.com/renatogroffe/CSharp12-PrimaryConstructorClass
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
The next listing exemplifies the use of a Primary Constructor in a struct called Demografia (line 3), with the values of the different declared parameters being associated with the Pais, Ano, and Populacao properties:
In the following code are examples of using the Demografia struct (including its Primary Constructor):
And when running this application we will have as a result:
This second Console Application has also been made available on GitHub:
https://github.com/renatogroffe/CSharp12-PrimaryConstructorStruct
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
*The content of this article is the author’s responsibility and does not necessarily reflect the opinion of iMasters.
Leave a comment