I have a Class named “Constants” that contains all the “constant” variable in my application (mostly Strings).
The Class is written like so:
public class Constants
{
public const string DATABASE="myDatabase";
public const string whatever="whatever";
public enum Colors
{
Red
Blue
Orange
}
public const string Time = "07/03/2009 9:14 PM";
}
The members of this Class can be accessed normally by other classes.
The weird thing is, if I remove the “const”, that variable can no longer be accessed on other classes.
public class Constants
{
public const string DATABASE="myDatabase";
public const string whatever="whatever";
public enum Colors
{
Red
Blue
Orange
}
public string Time = DateTime.Now.ToString(); //NO LONGER CONST
}
I tried to CLEAN the solution and rebuilding. I also closed/re-run VS2005. Is this a known bug? Or am I missing something else?
Thanks!
Once you remove the
constmodifier the variable becomes an instance variable. Instance variables can only be accessed through an instance of the class (not through the type). This is “By Design”.You would need to use code like the following to access Time
If “const” doesn’t suit your need for some reason, particularly if you are using a type which cannot be const, you may want to try static instead. It will have the same effect in terms of access semantics.