Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Consts in a public class

Tags:

string

c#

.net

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

like image 324
Belliez Avatar asked Nov 28 '22 11:11

Belliez


2 Answers

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.

like image 186
Svish Avatar answered Dec 07 '22 22:12

Svish


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.

like image 31
Jon Skeet Avatar answered Dec 08 '22 00:12

Jon Skeet