Does the order of read-only variable declarations indicate the order in which the values ββare set?
Tell me that I should have multiple read-only variables for file paths, can I guarantee the order in which these values ββare assigned based on the order of declaration?
eg.
static readonly string basepath = @"my\base\directory\location";
static readonly string subpath1 = Path.Combine(basepath, @"abc\def");
static readonly string subpath2 = Path.Combine(basepath, @"ghi\klm";
Is this a safe approach or is it possible that it basepath
could still be the default for the string at a point in time subpath1
and subpath2
make a reference to the string?
My understanding is that I could probably guarantee the order by assigning the values ββin the constructor and not during the declaration. However, I believe this approach would not be possible if I needed to declare variables inside a static class (e.g. Program.cs for a console application that has a static void Main () procedure instead of a constructor).
UPDATE:
I added the static keyword (how this is what I am using and why it compiles) as well as Path.Combine as suggested.
a source to share
Order doesn't matter. The runtime ensures that all objects are initialized when they are used.
Your particular case doesn't actually compile because it can't be guaranteed.
And you're right about the constructor approach. And if you need it for static variables, this is not a problem, because you can specify a static constructor.
And btw: The correct way to concatenate directories is to use Path.Combine, not string concatenation.
a source to share
I suspect you really want to use constants:
const string basepath = @"my\base\directory\location";
const string subpath1 = basepath + @"\abc\def";
const string subpath2 = basepath + @"\ghi\klm";
subpath1 / 2 the basepath prefix will be necessarily filled regardless of the order of declaration in the code.
a source to share