Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# variable names with special character

Tags:

c#

.net

c#-4.0

I want to include some special characters in a string variable name in C#.

Example: string foo-bar = String.Empty;

As far as my understand I can't declare a variable as I mentioned in the above example. Is there any way around to declare a variable name with "-" included?

like image 511
kranthiv Avatar asked Dec 04 '22 05:12

kranthiv


2 Answers

From MSDN:

You can't just choose any sequence of characters as a variable name. This isn't as worrying as it might sound, however, because you're still left with a very flexible naming system. The basic variable naming rules are as follows:

The first character of a variable name must be either a letter, an underscore character (_), or the at symbol (@). Subsequent characters may be letters, underscore characters, or numbers.

like image 93
Muhammad Obaidullah Ather Avatar answered Jan 03 '23 06:01

Muhammad Obaidullah Ather


No, this is not possible to do in C#.


If you really, really, really want to so this, you could use a Dictionary<string, string>:

Dictionary<string, string> someVars = new Dictionary<string, string>()
                                      {
                                          {"foo-bar", String.Empty},
                                          {"bar-foo", "bazinga"}
                                      }

Using them would look like this:

string newstring = someVars["foo-bar"] + "Hello World!";

Instead of just using the variable name, you would look up the string in your dictionary. Note that this is very inefficient and just intended as a joke, so please do no really use this ;)

like image 20
ThreeFx Avatar answered Jan 03 '23 06:01

ThreeFx