Reputation: 11961
I have this code Here:
var directories;
if (filePath == "")
{
directories = Directory.GetDirectories(filePath);
}
else
{
directories = Directory.GetDirectories(myPath);
}
But I get this error when defining the variable:
Implicitly-typed local variables must be initialized
Why am i getting this error and how would I go about fixing it?
Upvotes: 0
Views: 1170
Reputation: 172628
You should understand that C# is strongly typed language. So compiler could not determine what directories
is at compile time.
var
keyword was introduced for anonymous type binding at compile time. So if you dont initilize the value of directories
it is unknown to the compiler as at runtime the actual type(value or reference) is taken and var
is nowhere in the picture.
So you can try like
string[] directories;
if (filePath == "")
{
directories = Directory.GetDirectories(filePath);
}
or if you want to use var only then you can use it like this:
var directories = (string)null;
if (filePath == "")
{
directories = Directory.GetDirectories(filePath);
}
You can also refer MSDN for details: Implicitly Typed Local Variables
Upvotes: 0
Reputation: 34844
The compiler cannot figure out what type directories
is because you did not initialize it.
Try this:
string[] directories;
Upvotes: 0
Reputation: 349
You can't use var without an assignment. It is the assignment that determines the type of a var. Just change to declare a specific type and you should be good.
Upvotes: 0
Reputation: 21897
When using var
, the compiler doesn't know what the type of directories
is unless you initialize while you declare it. You have to declare a type if you're initializing later.
string[] directories;
if (filePath == "")
{
directories = Directory.GetDirectories(filePath);
}
//etc
Upvotes: 2