How to verify condition outside of a method

227 Views Asked by At

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.

2

There are 2 best solutions below

2
x00 On BEST ANSWER

Will this suffice? https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Static constructors are also a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints (Type parameter constraints).

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

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.

0
fanuc_bob On

If you have the type as you state that it's defined somewhere else in the project you could just create the list from the enum.

using System.Linq;

enum Stuff
{
  UglyStuff,
  BrokenStuff,
  HappyStuff
}

public class MyStuff
{
  public static List<string> MyList => System.Enum.GetNames(typeof(Stuff)).ToList();
}