7

var keyword gets the type at the runtime or compile time?

or depends?

DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • This has been discussed at other questions, including [C# 'var' vs specific type performance](http://stackoverflow.com/questions/356846/c-var-vs-specific-type-performance) and [ What's the difference between dynamic(C# 4) and var? ](http://stackoverflow.com/questions/961581/whats-the-difference-between-dynamicc-4-and-var). – Matthew Flaschen Sep 03 '10 at 03:57
  • 3
    it doesnt show up in the suggestions dude. implement a better algorithm for that. i m not telephatic. – DarthVader Sep 03 '10 at 04:00
  • And I'm not a SO developer, plus I didn't vote to close. I added the links so people could go there for more info. – Matthew Flaschen Sep 03 '10 at 04:05
  • Related http://stackoverflow.com/questions/3555625/var-reference-in-c-is-boxing/3555656#3555656 – Brian Rasmussen Sep 03 '10 at 04:29
  • See [var-reference-in-c-sharp-is-boxing](http://stackoverflow.com/questions/3555625/var-reference-in-c-sharp-is-boxing) – nawfal Jul 15 '14 at 14:14

3 Answers3

20

Plain and simple: compile time

var isn't a type. The actual type is figured out at compile-time.

var variables are also known as Implicitly Typed Local Variables (C# Programming Guide)

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • i ve been trying to come up with a case that type wont be known until runtime, is that possible? – DarthVader Sep 03 '10 at 03:52
  • @user, no. If the compiler can't determine the type, compilation will fail. – Matthew Flaschen Sep 03 '10 at 03:58
  • 2
    You should check the new `dynamic` keyword in C# 4.0. http://msdn.microsoft.com/en-us/library/dd264736.aspx – Leniel Maccaferri Sep 03 '10 at 03:58
  • @Leniel Macaferi, the Type is known by the compiler, even in the case of the dynamic Type. The compiler is merely unaware of the capabilities of any particular instance of the dynamic Type. – Amy B Nov 18 '11 at 16:16
4

var type gets at compile time .

Var is an implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type

var i = 10; // implicitly typed
int i = 10; //explicitly typed

http://msdn.microsoft.com/en-us/library/bb383973.aspx

anishMarokey
  • 11,279
  • 2
  • 34
  • 47
1

The var keyword is implicitly typed. This means that it is strongly typed, but the compiler determines the type.

Rebecca Chernoff
  • 22,065
  • 5
  • 42
  • 46