We help IT Professionals succeed at work.

C# constant

sepknow
sepknow asked
on
Is this possible?

I have a class that defines all the constant in my application:
public class MyConstant
{
     public static readonly string abc = "some name";
     //...
     //...
    public static readonly int xyz = 1024;
     //...
     //...
}

It is quite inconvenient to browse through the list, thousands of them.
I would like to re-goup them within this class such that I can acess them something like this:
string a = MyConstant.Group1.abc;
int x = MyConstant.Group2.xyz;

Is it possible?
Comment
Watch Question

The easiest way to do this is:

public class GroupSettings1
{
  public static readonly string abc = "abc";
  public static readonly int xyz = 1024;
}

public class MyClass {
  public static readonly GroupSettings1 Group1 = new GroupSettings1();
}
icr
Commented:
A static class would be better than a non static class I think, as you don't have to instantiate it. In order to get the nested settings you can utilise namespaces:

namespace MyApp.MyConstant
{
    public static class Group1
    {
        public static readonly int xyz = 1024;
        public static readonly string abc = "abc";
    }
}

This has the advantage that you can break the groups out into different files if you wish (though you can just place them one after the other in the same file).

If you have no other reason to make it a static readonly variable, why not make it an actual constant?

public const in xyz = 1024;

This means the compiler can optimise it a lot more aggressively for performance benefits (e.g. it can inline it). Not everything can be made const - if it needs instantiation, but for that you can then just use static readonly with a static constructor.
Thanks for the points :)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.