Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about the usage of var keyword

Tags:

c#

.net

I want to have something like:

var somevar;
if (cond)
{
  var= something;
  // a lot of code
}
else var = somethingElse;

However the compiler screams that a var should be initialized before using it in this way. How to do it. or how to accomplish this situation?

like image 930
Elena Avatar asked Dec 02 '22 03:12

Elena


2 Answers

You can't. When using var, you have to initialize the variable in the declaration...otherwise there is no way the compiler knows what type to make it.

Variables defined using var are still statically typed...the compiler just infers the type based on the assignment in the declaration. If you're looking for something that is dynamically typed, you could try the dynamic type if you're using .NET 4.0.

In your case, you need to specify the type at declaration.

like image 62
Justin Niessner Avatar answered Dec 04 '22 16:12

Justin Niessner


As other's have mentioned, var is still a static type, it just means that the compiler infers that type at compile time, not runtime.

I think this is what you want:

object somevar;
if (cond)
{
  somevar = something;
  // a lot of code
}
else somevar = somethingElse;
like image 23
CodingGorilla Avatar answered Dec 04 '22 17:12

CodingGorilla