Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is var different than other keywords? [duplicate]

Tags:

c#

c#-3.0

I just found out that you can use var as fieldname.

var var = "";

Why is this possible? Any other keyword as fieldname would not compile.

var string = ""; // error
like image 799
boop Avatar asked Aug 02 '19 12:08

boop


2 Answers

Well, string is a keyword

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/

we can't use it as an identifier:

// doesn't compile
var string = "";
// doesn't compile as well
int string = 123;

However, we can put String (capitalized) identifier

var String = ""; 
string String = "";
String String = "";

On the contrary var is not a keyword, it's a contextual keyword only (i.e. it's a keyword in some contexts only); that's why the lines below are correct ones:

string var = "";
int var = 123;
var var = "";
like image 68
Dmitry Bychenko Avatar answered Oct 17 '22 03:10

Dmitry Bychenko


In addition to other answers, string is a keyword of the language and you can not declare a variable with this name. This is also applied to other keywords like int, double, char, event etc. You can use the @ to escape this name. For sample:

var @string = "This is a string";
var @var = "This is a string declared named var";
var @int = 123;
var @double = 10.42;

And everytime you need to use it, you have to use the @. For sample:

Console.WriteLine(@string);

It is not a good pratice, avoid this kind of name to variables, objects, arguments, methods, etc.

like image 38
Felipe Oriani Avatar answered Oct 17 '22 03:10

Felipe Oriani