C# Static cast char to string

Viewed 187

I am trying to declare a constant char to hold a key and a constant string to hold a message telling the user to press the key:

...
private const KEY = 'r';
private const string MSG = "Press " + KEY + " to restart.";
...

I need to explicitly cast the key char to a string since the implicit cast is done during runtime. However, I can't figure out the way to cast a character to a string at compile time. I've seen ToString () on the internet, but it's performed at runtime and therefore doesn't work. I have the key char as a separate variable because it is used several times in the program. Does anybody know how to statically cast a char to a string?

2 Answers

The short answer is that you can't compose a string with anything other than string fragments.

You have a few options though. You can make both constants string types:

private const string KEY = "r";
private const string MSG = "Press " + KEY + " to restart.";

Another option would be to compose the string at runtime:

private const char KEY = 'r';
private static string MSG => "Press " + KEY + " to restart.";

You can't const string with other values which is const.

You can try to use readonly.

readonly can only modify values ​in the class constructor method, it will set that value at runtime.

private const char KEY = 'r';
private readonly string MSG = "Press " + KEY + " to restart.";
Related