derekl
asked on
Namespaced constants?
I have a class writtne in Java with a large number of constants that I am currently porting to C#. I nested the constants in Java so that the code would be a bit more readable:
public class Class1
{
public static final class CONSTANTS
{
public static final String CONST1 = "CONST1";
public static final class NESTED
{
public static final String CONST2 = "CONST2";
}
}
}
I can then access the constants using code like:
String strTemp1 = Class1.CONSTANTS.CONST1;
String strTemp2 = Class1.CONSTNATS.NESTED.CO NST2;
How could I do something similar in C#? I know that C# supports nested classes, but I also notice you cannot declare the class static. Does this mean every instance will get a separate copy of the class?
I've got only 70 points, and I'm putting them all up.
Thanks,
Derek
public class Class1
{
public static final class CONSTANTS
{
public static final String CONST1 = "CONST1";
public static final class NESTED
{
public static final String CONST2 = "CONST2";
}
}
}
I can then access the constants using code like:
String strTemp1 = Class1.CONSTANTS.CONST1;
String strTemp2 = Class1.CONSTNATS.NESTED.CO
How could I do something similar in C#? I know that C# supports nested classes, but I also notice you cannot declare the class static. Does this mean every instance will get a separate copy of the class?
I've got only 70 points, and I'm putting them all up.
Thanks,
Derek
ASKER
Thanks Tincho! What are the implications of the fact that I cannot declare the inner class Static. Does this mean every instance of the class I get will contain an instance of the Constants classes?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I think I understand now. The definition of class MyInnerClass is associated with MyClass. I won't ever have an instance of MyInnerClass unless I actuall create either from within MyClass or from without as follows:
MyClass.MyInnerClass = new MyClass.MyInnerClass();
MyClass.MyInnerClass = new MyClass.MyInnerClass();
right.
That's right
.. and a constuctor marked as private will enforce this.
You can always do:
public class MyClass
{
public const static string MyString = "My String";
public class MyInnerClass
{
public const static string MyOtherString = "My Other String";
}
}
and you would call them using
MyClass.MyString
and MyClass.MyInnerClass.MyOth
Hope this helps
Tincho