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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With