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.
source share