内容简介:Some time ago I came across Jimmy Bogard’s articleAs I’ve mentioned before, in order to make a class immutable we need to remove setters, add a dedicated constructor for initializing those properties and then always use this constructor to instantiate our
Some time ago I came across Jimmy Bogard’s article “Immutability in DTOs?” about the pros and cons of using immutable type pattern/approach. I fully agree with the author - the idea of immutable types is great but without the proper support from the language syntax it might not be worth applying. C# allows creating immutable types by adding readonly
keyword to fields or by removing setter from properties. We are obligated then to initialize those readonly members from the constructor or directly in the member’s definition. This results in a large amount of boilerplate code, causes problems with ORMs and serializers which require a default constructor, and makes the object instantiation cumbersome (or at least less readable). I’m a huge fan of Roslyn
so I’ve started thinking about how to utilize Roslyn’s API to avoid all those problems with immutable types and improve coding experience while working with them. In this article, I’m going to present the results of my experiments with Roslyn analyzers that simulate types immutability.
Convenient initialization
As I’ve mentioned before, in order to make a class immutable we need to remove setters, add a dedicated constructor for initializing those properties and then always use this constructor to instantiate our immutable class. A sample code snippet just to remind you how cumbersome it is:
public class UserDTO { public string FirstName { get;} public string LastName { get;} public int Age { get; } public UserDTO(string firstName, string lastName, int age) { FirstName = firstName; LastName = lastName; Age = age; } } class Program { static void Main(string[] args) { var user = new UserDTO("John", "Doe", 20); } }
It would be more convenient if we didn’t need to define a constructor and initialize members using the initialization block. However, there’s no mechanism that allows enforcing mandatory initialization in the init block. So, let’s introduce [InitRequired]
attribute inspired by initonly
keyword from C# records proposal :
If we want to enforce mandatory initialization via initialization block for all members, we can mark our type with [InitRequired]
attribute.
Of course, the property to be able to initialize via init block it must meet certain conditions:
- must have a setter
- the setter needs to be available in a given context (accessibility)
- cannot be a part of explicit interface implementation.
In order to avoid missing initialization caused by the conditions mentioned above, I would recommend always keeping those properties on the same accessibility level as the containing type.
Pro Tip:You can use MappingGenerator to complete initialization block with local accessible values or to scaffold this initialization with sample values
If you don’t have access to the source code or you want to enforce full initialization only for given instance, you can do that by adding /*FullInitRequired*/
comment marker:
To ensure that full object graph is initialized, use /*FullInitRequired:recursive*/
comment marker. I think this may be especially useful for methods performing mapping or deep clone. I got the idea of those comment markers from a discussion about String Hints #2796 . This kind of annotation is already used for marking string literals with regex pattern:
[InitRequired]
attribute enforces only mandatory initialization via initialization block. To achieve immutability, we need to forbid modification outside the init block. For that purpose, I’ve introduced [InitOnly]
attribute. Basically, it works in the same way as [InitRequired]
but additionally it verifies if members decorated with it are not modified after initialization.
You can enforce immutability for all members by putting [InitOnly]
attribute on the type level.
Thanks to [InitOnly]
attribute and corresponding analyzer we can achieve full immutability without writing redundant boilerplate code.
Important:If you like the idea of [InitRequire]
and [InitOnly]
attributes and you are going to use them in your project, please make sure that all your teammates know about it.
All attributes and analyzers described here are available as a single Nuget package SmartAnalyzers.CSharpExtensions.Annotations . The source code is published on Github
under CSharpExtensions project. Please let me know what you think about those extensions to C# language and if you encounter any problems with using it, feel free to report an issue on Github page.
If you find this blog post useful and you think it's worth to share this idea with others, please don't hesitate to use these buttons below:
以上所述就是小编给大家介绍的《Immutable types in C# with Roslyn》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
左手打工,右手创业
韩垒 / 东北师大 / 2011-4 / 29.80元
《左手打工右手创业》内容简介:打工一族,不能没有激情,不能没有梦想,激情能让你战胜困难,勇往直前;同时,要让梦想变成现实,你还必须具备务实的态度和实干的精神,一步一步向目标前进。创业不是简单的乌托邦式的理想,不是仅凭一腔热血加美好梦想就能顺利到达胜利的彼岸。个人创业更多的是要依靠前期科学的规划、多角度的观察、理性的分析、有效的资源分析与整合、成熟高效的运作技能、良好的商业心态等。 《左手打工......一起来看看 《左手打工,右手创业》 这本书的介绍吧!