tags:

views:

105

answers:

3

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# ?

+6  A: 

Use @ for reserved words:

@class=>"hello"
Darin Dimitrov
+12  A: 

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 :)

Andrew Bezzub
Those pooooooor kittens!
Randolpho
+1 for admonishment.
Forgotten Semicolon
@Andrew Bezzub, I can see how it can be seen as bad practice. But I need it for a very specialized scenario that will take way too long to explain the details here. Having said that, I would like to hear your thoughts on why ***you*** think this is bad practice.
Roberto Sebestyen
There is a reason why some works are _key_ words. the only reason i can think of to do this is if you're writing a compiler or some kind of parser. However, why is having a variablename which is not a keyword not an option, there are infinite many possibilities to do so. even using classInstance is better than @class.
Henri
@Roberto Sebestyen, all variables should have such names that it would be very easy for anyone to understand what is each variable for. I don't think having variable with name 'class' tells much about it. If you have a case when you think it can be useful then please tell me, I haven't met such cases in real world projects.
Andrew Bezzub
Another reason why you might want to use this feature: suppose you define your own domain-specific language, and then write a translator that translates your DSL into C#, rather than writing your own compiler. The reserved words of your DSL might not be the reserved words of C#; a user of your DSL might reasonably want to make a property named "class" or "event". If your code generator generates @class or @event then you don't have to work out some more complex scheme of encoding the translation from DSL to C#.
Eric Lippert
Without going into great detail, I am actually working on something that involves generating HTML, CSS and Javascript from strongly typed C# code. The key word 'class' can be a key word for both in HTML and C#, which is why I needed to escape it in C#.
Roberto Sebestyen
+3  A: 

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.

klausbyskov