Anti-Patterns with CONSTANTS.

I have a habit that’s probably an anti-pattern. I like to nest classes in a constants file.

  1. I always call the file Constant.cs. Singular. It goes at the root level of my Framework project. This should be accessable from every other project within your solution.
  2. The class is a static. Therefore, all of the subclasses are static as well.

Normal Constant file

public static class Constant
{
  public const string Title = "My Title";
  public const string EmailAddress = "foo@bar.com";
 }

Now consider this…

Nested classes

public static class Constant
    {
 
        public const string Title = "My Title";
        public const string EmailAddress = "foo@bar.com";
 
        public static class Color
        {
            
            public static class White
            {
                public const string Name = "White";
                public const string HexCode = "#FFFFFF";
            }
 
            public static class Black
            {
                public const string Name = "Black";
                public const string HexCode = "#000000";
            }
 
        }
 
    }

Usage

public class Usage
    {
        public void Example()
        {
            var blackHexCode = Constant.Color.Black.HexCode;
        }
    }

I like how this creates a clean hierarchy to reference a constant. As I said, this is probably an anti-pattern. But it works for me.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.