How to warn if a resource is accessible without initialization by adding an attribute?

I would like some method to automatically replace the following code:

[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; } } 

I would prefer a solution that works at compile time, since reflection is slow.

I know that Aspect Oriented Programming (AOP) will do this (like PostSharp and CciSharp), but I would be wondering if there is any other method for this.

Update

See How to use PostSharp to warn if a property has access before it was initialized? which has a link to some sample code that demonstrates the technique using PostSharp.

+4
source share
5 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

0
source

Attributes simply add metadata to classes and class members - they themselves do nothing.

Operations performed with decorated members are performed using reflection - some of the existing tools have some support, but there will be no such support for user attributes.

In short, you cannot check an attribute at compile time if the compiler does not yet support it.

However, you can create your own code snippets to make such code easier to write and create.

+2
source

T4 templates can be used to generate code. I did not realize myself, but T4 templates are used to generate C # code. More info from scott hanselman

http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx

0
source

Only some attributes are checked by compilation. ObsoleteAttribute and ConditionalAttribute are two of them. Using Resharper, you may receive such warnings. I do not know any other tool that can do this.

0
source

You can make an implementation similar to .NET Lazy, but using this property will require a bit more verbosity. Something like this unsafe example:

 public class WarnIfGetButUninitialized<T> { T _property; public T Value { get { if(_property == null) { Console.WriteLine("Error: cannot fetch property before it has been initialized properly.\n"); return default(T); } return _property; } set { _property = value; } } } 
0
source

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


All Articles