How to use PostSharp to warn if a property has access before it was initialized?

How can I use PostSharp to replace this:

[WarnIfGetButUninitialized] public int MyProperty {get; set; } 

Wherein:

 /// <summary> /// Property which warns you if its value is fetched before it has been specifically instantiated. /// </summary> private bool backingFieldIsPopulated = false; private int backingField; public int MyProperty { get { if (backingFieldIsPopulated == false) { Console.WriteLine("Error: cannot fetch property before it has been initialized properly.\n"); return 0; } return backingField; } set { backingField = value; backingFieldIsPopulated = true; } } 

Refresh

I should also add that this is a good method to improve code reliability. In a project with 20,000 lines, it's nice to know that everything is correctly initialized before using it. I intend to use this to build the Debug and remove it in the Release build, because I don't want to slow down the final release unnecessarily.

+1
source share
2 answers

From Gael Fraiteur on the PostSharp forum (thanks Gael!):

You should use a LocationInterceptionAspect that implements IInstanceScopedAspect. The "backingFieldIsPopulated" field becomes the aspect field.

In this example, you can find inspiration:

http://doc.sharpcrafters.com/postsharp-2.1/Content.aspx/PostSharp-2.1.chm/html/d3631074-e131-467e-947b-d99f348eb40d.htm

+1
source

What about the fact that your constructor initializes it correctly and you don’t need to worry about it?

+1
source

Source: https://habr.com/ru/post/1393354/


All Articles