I'm opening old C# code from my work using Reflector and I found out that there was an enum in an SQL class which looked like this:
public enum Column
{
bool,
...
}
The enum is populated with column types and it doesn't compile due it being a reserved keyword. Obviously someone was able to compile it at some point. How do I get it to compile?
Thanks!
You need to prefix with a character literal (# symbol) in order to use keywords.
MSDN (Thanks #erikH)
Related
I want to do the equivalent of the following VB in c#
Function([class]) "hello"
This would be the same as this in c#
class=>"hello"
The problem is that the word class is a key word in the language. But I want to use it as a variable name. In the VB example you can use the [] brackets to 'escape' that key word and allow it to be used as a variable name.
Is there a way to do this in C# ?
You need to add # to variable names:
#class
But it is a very bad practice. Every time you name your variable as a keyword a kitten dies :)
Use # for reserved words:
#class=>"hello"
You can prefix any keyword with a #.
But I don't think it's a recommended practice, and code analysis complains about it for sure.
I'm designing an application that requires a "location" field. The values for the location are "3241", "4112", "ND" and "TRAVEL", and I am trying to set up an enum that includes those values.
I started with
enum projectLocation {3241,4112,ND,TRAVEL};
but the values 3241 and 4112 indicated a syntax error--identifier expected--for the first value in the enum. If I understand enum correctly, that's because the above statement is looking for the value for the enum's integer indeces of 3241 and 4112. Is this a correct assumption?
I tried overriding that with the following
enum projectLocation {3241=0,4112,ND,TRAVEL};
and
enum projectLocation {3241=0,4112=1,ND=2,TRAVEL=3};
but I'm still getting the same syntax error on the 3241 value. Interestingly though, on both of these statements, there is NO syntax error on 4112, but I get can't find the namespace or name ND and ...TRAVEL
It makes sense that enum will not allow a mix of strings and integers, and I have two other enums that work fine and are only lists of string values, corroborating that theory. Is there a way to force enum to accept the numeric values as strings? I've not been able to find any references in MSDNs C# documentation.
Enums are called as named constants, so basically you give a name for some constant. Names are "identifiers" in c#, where identifier can contain numbers but first character cannot be a number.
You can add _ before that to fix this error.
enum projectLocation
{
_3241=0,
_4112=1,
ND=2,
TRAVEL=3
}
Also note the Fields, Properties Methods or whatever falls under this identifier rule mentioned above.
You can't do it exactly like you're trying to. Here's an alternative:
enum projectLocation {
L3241=3241,
L4112=4112,
ND=2,
TRAVEL=3
}
Starting them with a letter makes them valid enum identifiers, and setting their value equal to their number lets you do things like (projectLocation)3241 and get the expected L3241 value.
If you need the values to be 3241 and 4112 when serialized, include the proper attribute for your serialization approach, e.g. with Json.NET:
enum projectLocation {
[JsonProperty("3241")]
L3241=3241,
[JsonProperty("4112")]
L4112=4112,
ND=2,
TRAVEL=3
}
You would need to do something like this:
enum projectLocation { v3241, v4112, ND, TRAVEL };
or:
enum projectLocation { _3241, _4112, ND, TRAVEL };
My preference would be the use of the underscore.
C# does not allow the first character of member names to start with a number. Consider using the # character as a prefix, or some other character that conveys a meaning useful to a reader of the code as a number in isolation may not be very intuitive to a reader not familiar with the significance of 3241 in your context.
Just curios is there any way to get the list of symbols that are illegal for naming variables in C# e.g. brackets of all kinds, commas etc in code? Something like SomeClass.GetIllegalVariableSymbols()
No; there are a lot, for one, when you consider Unicode, and there are also other rules (e.g. an identifier can contain a number but not begin with one, keywords can’t be used as identifiers unless prefixed by an #, etc.).
You’ll need to build your own appropriate for the situation. (What is that, out of curiosity?)
Yes, you can. Just use Path.GetInvalidFileNameChars() method.
Source
I'm trying to use a DLL generated by ikvmc from a jar file compiled from Scala code (yeah my day is THAT great). The Scala compiler seems to generate identifiers containing dollar signs for operator overloads, and IKVM uses those in the generated DLL (I can see it in Reflector). The problem is, dollar signs are illegal in C# code, and so I can't reference those methods.
Any way to work around this problem?
You should be able to access the funky methods using reflection. Not a nice solution, but at least it should work. Depending on the structure of the API in the DLL it may be feasible to create a wrapper around the methods to localise the reflection code. Then from the rest of your code just call the nice wrapper.
The alternative would be to hack on the IL in the target DLL and change the identifiers. Or do some post-build IL-hacking on your own code.
Perhaps you can teach IKVM to rename these identifiers such that they have no dollar sign? I'm not super familar, but a quick search pointed me at these:
http://weblog.ikvm.net/default.aspx?date=2005-05-02
What is the format of the Remap XML file for IKVM?
String and complex data types in Map.xml for IKVM!
Good Hunting
Write synonyms for those methods:
def +(a:A,b:A) = a + b
val plus = + _
I fear that you will have to use Reflection in order to access those members. Escaping simply doesn't work in your case.
But for thoose of you, who interested in escaping mechanics I've wrote an explanation.
In C# you can use the #-sign in order to escape keywords and use them as identifiers. However, this does not help to escape invalid characters:
bool #bool = false;
There is a way to write identifiers differently by using a Unicode escape sequence:
int i\u0064; // '\u0064' == 'd'
id = 5;
Yes this works. However, even with this trick you can still not use the $-sign in an identifier. Trying...
int i\u0024; // '\u0024' == '$'
... gives the compiler error "Unexpected character '\u0024'". The identifier must still be a valid identifier! The c# compiler probably resolves the escape sequence in a kind of pre-processing and treats the resulting identifier as if it had been entered normally
So what is this escaping good for? Maybe it can help you, if someone uses a foreign language character that is not on your keyboard.
int \u00E4; // German a-Umlaut
ä = 5;
I have some client data that I am reading in, and I've defined an Enum for one of the values, so I can use Enum.Parse(type, somestring).
The problem is they just added a new value: "public". Is it possible to define an enum value that is also a reserved word?
I.E.:
public enum MyEnum {
SomeVal,
SomeOtherVal,
public,
YouGetTheIdea
}
If not I guess I'll be writing a parse method instead.
You can prepend a # to the variable name. This allows you to use keywords as variable names - so #public.
See here.
From the C# spec:
The prefix "#" enables the use of keywords as identifiers, which is useful when interfacing with other programming languages. The character # is not actually part of the identifier, so the identifier might be seen in other languages as a normal identifier, without the prefix. An identifier with an # prefix is called a verbatim identifier. Use of the # prefix for identifiers that are not keywords is permitted, but strongly discouraged as a matter of style.
yes, prefix the name with an #. i.e. #public
If you capitalize public to Public it won't be recognized as a keyword. Keywords are case sensitive.
As a general practice, however, it's a bad idea to use names that are keywords (even when they differ by case) as it can cause confusions, or even subtle defects if the keyword is accidentally used in place of the identifier.
It's also possible to use the # in certain contexts (like variable or member declarations) to use reserved words as non-keywords. However, it's not a common practice and should only be a means of last resort, when you can't use a different name.
So in your case you could also use #public to use the reserved word as an enum identifier.
If you chose to use #, be aware that the symbol is only used in your source code to differentiate the identifier from the reserved word. To the outside world (and in methods like Enum.Parse()), the name of the enum value is simply public.
It's not really a great idea to do this though. Instead, add a bit more info to the enum:
PublicAccess etc
In VB.Net use square braces [...] to delineate a keyword as an identifier.
Example:
Public Sub Test(ByVal [public] As String)
MessageBox.Show("Test string: " & [public])
End Sub
For VB.NET do the following:
Public Enum MyEnum As Integer
Disabled = 0
[New] = 1
[Public] = 2
Super = 4
[Error] = 5
End Enum