Just curious, is there a way to have a getter for a constant variable? I have a sort of internal version number to ensure that two versions of a library are still speaking the same language, but I’d like the programmer to be able to check what version they’re using. Right now I use:
private const Int16 protocol_version = 1;
public Int16 ProtocolVersion => protocol_version;
But I’d prefer to do it with just the const if there’s a way.
You could declare a property with only a get accessor (without even declaring the set accessor, not even private):
This is not the same as defining a constant only: the constant would be resolved at compile time, so if you update the library without recompiling the dependent program, the program would still see the "old" value. Consider this example:
Now, compile the first time and execute the program. You will see
Then, modify protocol_version to 2, and recompile the class library only, without recompiling the program, then put the new class library in the program folder and execute it. You will see:
The fact is that if it’s just a constant, the value is replaced at compile time.
I think that what you are actually looking for is a
static readonlyvariable: in that way, you will avoid the compile-time const replacement, and the variable will not be modifiable after initialization: