5

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
boop
  • 7,413
  • 13
  • 50
  • 94
  • 2
    [This](https://blogs.msdn.microsoft.com/ericlippert/2009/05/11/reserved-and-contextual-keywords/) has some insight on the topic – steve16351 Aug 02 '19 at 12:29
  • [var](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var) appears from C# 3.0, if it would become reserved keyword, then this change would break a lot of code. – Sinatr Aug 02 '19 at 12:37
  • Just because I think it fits somehow, here is [basically the same question for Java](https://stackoverflow.com/q/49089124/3182664) – Marco13 Aug 02 '19 at 15:57

2 Answers2

8

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 = "";
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

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.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • You are probably missing "in addition to other answer" at the beginning of answer. I was confused to read about `@` when question is about allowed `var var`. – Sinatr Aug 02 '19 at 12:41