Is there a way to verify the integrity of a class variable at the point in the code where it is created?
For example, I create and initialize a class member variable like this:
public class MyClass
{
public static Dictionary<MyEnum, int> SomeDictionary = new Dictionary<MyEnum, int> {
{ MyEnum.First, 9 },
{ MyEnum.Second, 7 },
{ MyEnum.Third, 17 }
};
// This obviously doesn't compile
Debug.Assert(<SomeDictionary contains good stuff>);
// Some method in my class
public void SomeMethod()
{
// I could use something like this in this method to verify
// the integrity of SomeDictionary, but I'd rather do this
// at the point (above) where SomeDictionary is defined.
Contract.Requires(<SomeDictionary contains expected stuff>);
}
}
As I point out in the code, I want to validate the contents of my data at "class" scope, but Debug.Assert and Contract.Requires only work in method (or property) scope.
EDIT: This question originally used a List whose contents are (tangentially) related to an Enum as an example, but people fixated on how that List was being derived from an Enum, NOT on the question of how to validate the List contents. So I totally rewrote the question to clarify that the question is about validation, NOT about building a data structure.
Will this suffice? https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
But unit tests can be better. If not for the fact that they are far from the code and must be written and maintained separately. But at least they have no runtime overhead.