I have a class below:
I want to access these default strings but C# compiler doesn’t like combining Const to create a Const.
public class cGlobals
{
// Some Default Values
public class Client
{
public const string DatabaseSDF = "database.sdf";
public const string DatabaseDir = "database";
public const string DatabaseFullLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
DatabaseDir);
public const string DataSource = Path.Combine(DatabaseDir, DatabaseSDF);
}
}
Is there a better way instead of hard coding the strings? I want to make use of the Special Folders and Path.Combine.
Thanks
You must use
static readonlyinstead ofconst, sinceconsthave to be a constant at compile-time.Also, constants will actually be compiled into assemblies that are using them, so if you are referencing those fields from other assemblies you would have to recompile them if you changed the constants. This doesn’t happen with
static readonlyfields. So either way, it’s a better idea 🙂I actually asked about this a while ago and I would recommend reading it and the accepted answer: static readonly vs const.