Gregory Sysoev
Gregory Sysoev

Reputation: 321

Can't set string const System.Environment.CurrentDirectory;

I have trouble initializing a const:

The expression being assigned to 'path' must be constant (CS0133)

My code:

using System;

namespace study
{
    class Program
    {
        static void Main(string[] args)
        {
            // Here I get this error
            const string path = System.Environment.CurrentDirectory; 

            // This here is ok
            string path = System.Environment.CurrentDirectory;
        }
    }
}

With .ToString() method - also have trouble.

Upvotes: 0

Views: 847

Answers (2)

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

You can't do this because constants are compile-time values. They cease to exist as a named entity when the program is compiled because the values are directly substituted (source: docs):

In this example, the constant months is always 12, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference and cannot appear as an l-value in an expression.

Even if this did work, you would only have the value of the current directory on the machine that compiled the code, not the machine that's running the code. That doesn't make much sense.

While you can't use this in methods, if you need global "constant"-esque values such as this, you can define them like so:

public static readonly string Path = System.Environment.CurrentDirectory;

Though why you wouldn't just use System.Environment.CurrentDirectory, I don't know.

Upvotes: 1

John
John

Reputation: 6278

The issue is that you're trying to assign a dynamic value to a constant variable.

The constant must be a literal string (or existing constant) and should not be reassigned.

Upvotes: 2

Related Questions