I have a local string (file path) which I need to retrieve from a function only once and I'd like to make sure it's never modified again. I cannot use the const
keyword because the value of my string is determined at runtime rather than compile time. So I tried using the readonly
keyword instead, but Visual Studio is telling me that it is not valid for my item. How can I achieve the level of protection I want, preferably without making another class?
For simplicity and company policy, I've (drastically) shrunk down and renamed my classes and functions, but the concept is the same.
public class myClass
{
private void myFunction()
{
readonly string filePath = HelperClass.getFilePath("123");
//do stuff
}
}
public static class HelperClass
{
public static string getFilePath(string ID)
{
switch(ID)
{
case "123":
return "C:/123.txt";
case "234":
return "C:/234.txt";
default:
throw new Exception(ID + " is not supported");
}
}
}
=== Edit For PS2Goat ====
public class myClass
{
protected SomeObject o;
private virtual readonly string path;
public myClass(someObject o)
{
this.o = o;
path = HelperClass.getFilePath(o.getID());
}
private virtual void myFunction()
{
//do stuff
}
}
public class myDerivedClass
{
private override virtual readonly string path;
public myDerivedClass(someObject o) : base(o)
{
path = HelperClass.getFilePath(o.getID()); //ID will be different
}
private override void myFunction()
{
//do different stuff
}
}
public static class HelperClass
{
public static string getFilePath(string ID)
{
switch(ID)
{
case "123":
return "C:/123.txt";
case "234":
return "C:/234.txt";
default:
throw new Exception(ID + " is not supported");
}
}
}
See, so this issue I'm having is that if I want to throw an exception, I'd have to catch it in the parent class' constructor for now (until that class is supported) because the parent constructor will be called before the derived constructor. So the wrong ID will be set once before the child constructor (which has the correct ID) is called.