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 readonly
instead of const
, since const
have 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 readonly
fields. 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.
For a variable to be declared const
, the assigned value has to be a compile-time constant; to use the result of a method call you need to change your variable declaration:
public static readonly string DataSource = ...;
If you think about it, this isn't a compile-time constant, in that it will give different results based on which OS you run it on. It's constant within a single execution but not a "general" constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With