Say I were to have a few readonly variables for filepaths, would I be able to guarantee the order in which the values are assigned based on the order of declaration?
e.g.
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 basepath may still be the default value for a string at the time subpath1 and subpath2 make a reference to the string?
I realize I could probably guarantee the order by assigning the values in a constructor instead of at the time of declaration. However, I believe this approach wouldn’t be possible if I needed to declare the variables inside of a static class (e.g. Program.cs for a console application, which has a static void Main() procedure instead of a constructor).
UPDATE:
I’ve added the static keyword (as that is what I am using and why it compiles) and also Path.Combine as suggested.
The order is unimportant. The runtime guarantees that all objects are initialized when they are used.
Your concrete case is actually not compilable because this could not be guaranteed.
And you are right about the constructor approach. And if you need this for static variables it’s no problem either because you can specify a static constructor.
And btw: The correct way of concatenating directories is to use Path.Combine and not string concatenation.