This question already has answers here:
What's the use/meaning of the # character in variable names in C#?
(9 answers)
Closed 9 years ago.
I was given a project of a some developer and during looking throuhg the code I found such code:
public interface IPackage
{
void #Do();
}
I've just seen usage of # in context with strings. But what does that mean in such context? Can somebody explain please? Thank you in advance!
From MSDN:
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.
The # character allows you to give your variables names that are reserved as keywords. A common and useful use case for this is:
public static void AnExtensionMethod(this SomeObject #this)
{
#this.AMethod();
}
In your example the # seems obsolete in C# as Do is not a keyword (do is). It is in VB.NET though, so if this interface will be consumed by VB.NET clients it is needed. In your case it is fine only if there really wasn't any better name for the method than Do. As it is now it seems not very readable. Conceptually "package.do" can mean anything so you can call it x as well. But maybe in your domain language this is a more precise term.
The documentation states:
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.
Related
The "#" character is allowed as a prefix to enable keywords to be used as identifiers.
Majority of .net developers know about this.
But what we may not know:
Two identifiers are considered the same if they are identical after the "#" prefix is removed.
So
static void Main(string[] args)
{
int x = 123;
Console.WriteLine(#x);
}
is absolutely valid code and prints 123 to the console.
I'm curious why do we have such rule in the specs, and how this feature may be used in real world situations (it doesn't make sense to prefix identifiers with "#" if they are not keywords, right?).
It is totally logical. # is not part of the name but is a special indicator to not treat what comes after as a keyword but as an identifier.
Eric Lippert has a very good post about it: Verbatim Identifier
I’m occasionally asked why it is that any identifier can be made into
a verbatim identifier. Why not restrict the verbatim identifiers to
the reserved and contextual keywords?
The answer is straightforward. Imagine that we are back in the day
when C# 2.0 just shipped. You have a C# 1.0 program that uses yield
as an identifier, which is entirely reasonable; “yield” is a common
term in many business and scientific applications. Now, C# 2.0 was
carefully designed so that C# 1.0 programs that use yield as an
identifier are still legal C# 2.0 programs; it only has its special
meaning when it appears before return, and that never happened in a C#
1.0 program. But still, you decide that you’re going to mark the usages of yield in your program as verbatim identifiers so that it is
more clear to the future readers of the code that it is being used as
an identifier, not as part of an iterator
Let's consider the example of a program that generates C# code -- for example, something that takes the columns in a database table and creates a comparable C# POCO object, with one property per column.
What if one of the column names matches a C# keyword? The code generator doesn't have to remember which words are keywords or not if all of the property names are prefixed with #.
It's a fail-safe. The extra # characters don't hurt the code at all!!
The other answers are pretty clear about why the behavior exists, but I think it might be worthwhile to look at the rules for which identifiers are treated as equal.
Quoting the specification section 2.4.2:
Two identifiers are considered the same if they are identical after the following transformations are applied, in order:
The prefix "#", if used, is removed
Each unicode-escape-sequence is transformed into it's corresponding Unicode character.
Any formatting-characters are removed.
Following those rules, #x is identical to x.
It provides certainty:
Using #word is future-proof.
No changes are needed if it becomes a keyword later.
Most programmers will not be familiar with every keyword (C# has approx. 100 keywords)
The more recent keywords are "contextual", so sometimes they are not keywords.
In my domain model I have an Event entity. This means that I have to sometimes declare variables as: #event since event is a reserved key word.
I've read on a few stack overflow posts (like What's the use/meaning of the # character in variable names in C#?) that this is not recommended unless you're interacting with other programming languages. My question is why is it not recommended? What is the issue with using #?
I could use an "Occasion" entity instead but that would mean in my UI layer I would have events which maps to occasions?
What you're trying to do is the entire purpose of the # prefix to prevent name clashes.
But this text from MSDN says everything you're asking:
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.
Source
So it just comes down to style, in your case it's the right solution if you don't want to rename your entity.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What are the naming guidelines for ASP.NET controls?
Is there a standard guidelines as to the naming convention/style that asp.net control elements should be named. I have seen some developers prefixing textboxes with txt etc. Are there any standards that should be abided by?
You can use ISO standard Naming convention or CMM level convention.
like Function name "Add"
variable name "strQuery"
Control Name "btnSubmit"
Class Name "Common"
Namespace "Sanjog.Web"
public Property Name "UniqueId"
private variable "_uniqueId"
Hope this is what you are looking for.
Prefixes like "txt" are more common with developers who came up through VB6, or learned from developers who came up through VB6. In a truly object-oriented environment such as .NET its not as necessary to prefix items to indicate their type. However, doing so it entirely a matter of personal preference, just be consistent.
There is no official standard for naming of controls.
Actually the naming convention is only for your convenience so that it can be reusable and some one who will be editing it or trying to understand it would not be a big deal for him
Now coming to the point Generally Naming conventions are followed in company level
i.e some use the prefix of textbox (like textBoxName , textBoxPassword), some txt ( like txtName). Everything is right .
It is just that all the developers in a team must follow the same and the same to be maintained through out the project.
MSDN has it covered -> MSDN Naming Guidelines
(follows an abstract from the linked page, too long to bring everything over)
Use the following three conventions for capitalizing identifiers.
Pascal case - The first letter in the identifier and the first letter of
each subsequent concatenated word are capitalized. You can use Pascal
case for identifiers of three or more characters.
For example: BackColor
Camel case - The first letter of an identifier is lowercase
and the first letter of each subsequent concatenated word is
capitalized.
For example: backColor
Uppercase - All letters in the identifier are capitalized.
Use this convention only for identifiers
that consist of two or fewer letters.
For example: System.IO, System.Web.UI
You might also have to capitalize identifiers to
maintain compatibility with existing, unmanaged symbol schemes, where
all uppercase characters are often used for enumerations and constant
values. In general, these symbols should not be visible outside of the
assembly that uses them.
Anyway, as long as everyone working on a project follows the same convention, you're good to go, whatever that convention is.
I am writing a code generator in which the variable names are given by the user.
Previous answers have suggested using Regex or CodeDomProvider, the former will tell you if the identifier is valid, but doesn't check keywords, the latter checks keywords, but doesn't appear to check all Types known to the code.
How to determine if a string is a valid variable name?
For instance, a user could name a variable List, or Type, but that is not desirable. How would I prevent this?
The easiest way is to add a list of C# keywords to your application. MSDN has a complete list here.
If you really want to get fancy, you could dynamically compile your generated code and check for the specific errors that you're concerned about. In this case, you're specifically looking for error CS1041:
error CS1041: Identifier expected; '**' is a keyword
You'll probably want to ignore any errors regarding unresolved references, undeclared identifiers, etc.
As others have suggested, you could just prepend your identifiers with #, which is fine if you don't want the user to examine the generated code. If it's something they're going to have to maintain, however, I'd avoid that as (in my opinion) it makes the code noisy, just like $ all over the place in PHP or guys that insist on putting this. in front of every freaking field reference.
I'm not sure there is a full API available which will give you what you're looking for. However the end result you seem to be looking for is the generation of code which will not cause conflicts with reserved C# keywords or existing types. If that is the case one approach you can take is to escape all identifiers given by the user with the # symbol. This allows even reserved keywords in C# to be treated as identifiers.
For example the following is completely valid C# program
class Program
{
static void Main(string[] args)
{
int #byte = 42;
int #string = #byte;
int #Program = 0;
}
}
One option here would be to have your code generator prefix the user-specified name with #. As described in 2.4.2, the # sign (verbatim identifier):
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.
This would allow you to check for the main keywords, and deny them as needed, but not worry about all of the conflicting type information, etc.
You could just prepend a # character to the variable - for instance, #private is a valid variable name.
I discovered that you can start your variable name with a '#' character in C#.
In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in C# so you can't have a class with a member variable with the name "params". The proxy object that was generated contained a property that looked like this:
public ArrayList #params {
get { return this.paramsField; }
set { this.paramsField = value; }
}
I searched through the VS 2008 c# documentation but couldn't find anything about it. Also searching Google didn't give me any useful answers. So what is the exact meaning or use of the '#' character in a variable/property name?
Straight from the C# Language Specification, Identifiers (C#)
:
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.
It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).
In C# the at (#) character is used to denote literals that explicitly do not adhere to the relevant rules in the language spec.
Specifically, it can be used for variable names that clash with reserved keywords (e.g. you can't use params but you can use #params instead, same with out/ref/any other keyword in the language specification). Additionally it can be used for unescaped string literals; this is particularly relevant with path constants, e.g. instead of path = "c:\\temp\\somefile.txt" you can write path = #"c:\temp\somefile.txt". It's also really useful for regular expressions.
Unlike Perl's sigils, an # prefix before a variable name in C# has no meaning. If x is a variable, #x is another name for the same variable.
> string x = "abc";
> Object.ReferenceEquals(x, #x).Dump();
True
But the # prefix does have a use, as you've discovered - you can use it to clarify variables names that C# would otherwise reject as illegal.
> string string;
Identifier expected; 'string' is a keyword
> string #string;
The # symbol allows you to use reserved keywords for variable name. like #int, #string, #double etc.
For example:
string #public = "Reserved Keyword used for me and its fine";
The above code works fine, but below will not work:
string public = "This will not compile";
It simply allows you to use reserved words as variable names. I wanted a var called event the other day. I was going to go with _event instead, but my colleague reminded me that I could just call it #event instead.
Another use case are extension methods. The first, special parameter can be distinguished to denote its real meaning with #this name. An example:
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> #this,
TKey key,
TValue defaultValue)
{
if (!#this.ContainsKey(key))
{
return defaultValue;
}
return #this[key];
}
If we use a keyword as the name for an identifier, we get a compiler error “identifier expected, ‘Identifier Name’ is a keyword”
To overcome this error, prefix the identifier with “#”. Such identifiers are verbatim identifiers.
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
You can use it to use the reserved keywords as variable name like
int #int = 3;
the compiler will ignores the # and compile the variable as int
it is not a common practice to use thought