0

If I have a string and I initialize it to string.Empty, then

var mystring=string.Empty;

or

string mystring = string.Empty;

Which of the above two should be better wrt performance or any other considerations?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Warrior
  • 139
  • 1
  • 3
  • 10

2 Answers2

3

var is an implicit type. It aliases any type in the C# programming language. The aliased type is determined by the C# compiler.

The var keyword has equivalent performance. It does not affect runtime behavior.

Your both codes generate same IL code;

IL_0000:  nop
IL_0001:  ldsfld     string [mscorlib]System.String::Empty
IL_0006:  stloc.0
IL_0007:  ret
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

They both compile to the same IL code, so there is no performance difference during code execution.

However, the second one is more readable, and I would go that way.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    Respectfully, my style is to always use `var` when I can. It I fine that we disagree, but to infer that one is better than the other on any basis than personal style is presumptious. – Pieter Geerkens Apr 12 '13 at 06:55
  • I think using `var` while you're initializing simple types, like `int`, `double` or `string` should be avoided, but as you said I's just an opinion. – MarcinJuraszek Apr 12 '13 at 06:56
  • 1
    I'm a huge `var` fan too: I don't want to care about types unless I must, being that the compiler is smart enough to allow me to. – Alex Apr 12 '13 at 06:57
  • One point: In the case of loop indices the use of `var` over `int` or `long` is explicitly recommended by MSDN guidelines – Pieter Geerkens Apr 12 '13 at 07:00