Share via


Consider replacing strings with Enums in resource references.

Consider replacing strings with Enums in resource references.

I see code like this all the time in test and XNA and I really dislike it.

 

            MyCustomResourceClass resources = new MyCustomResourceClass();

            MyImageClass currentImage = resources["Image 1.jpg"];

I dislike because it’s nearly impossible to tell where the list of valid resources lives. You don’t want to put a comment on every reference to the resources class. Some /// documentations in the resources class might help, but you probably want to keep it generic.

 

I prefer a pattern that looks like this.

            //List of resources in the MyImages.XML file from the resources Directory.

            enum AvailableImages

            {

                Image1,

                Image2,

                Image3

            }

      …

           MyImageClass nextImage = resources[AvailableImages.Image2];

You do incur overhead maintaining the enum, but it makes your code much clearer and promotes run time errors to compile time errors. Remember you can add descriptions to the enums if you have to do something like map to filenames with spaces in them. Then the resources class can have some intelligent code for looking up the file names.