Yes it is just a statement. There are not any major differences between the two. Unassigned variables are initialized with the default value for the data type when the program runs. The only time you will run into an issue with unassigned variables is if you assign it in if
blocks and don't have an else
statement and then attempt to use the variable outside the scope of the if
block. The compiler will throw an error saying that the variable is potentially unassigned in this case. Ex:
string testString;
if (some condition here)
testString = "Success";
if (testString == "Success") //This line will throw an error because testString may be unassigned
string testString = "Failure";
if (condition)
testString = "Success";
if (testString == "Success") //No error this time becuase testString was initialized with a value
string testString;
if (condition)
testString = "Success";
else
testString = "Failure";
if (testString == "Success") //No error here because all paths will assign a value to testString
Edit from Microsoft:
Initially assigned variables
The following categories of variables are classified as initially assigned:
- Static variables.
- Instance variables of class instances.
- Instance variables of initially assigned struct variables.
- Array elements.
- Value parameters.
- Reference parameters.
- Variables declared in a catch clause or a foreach statement.
Initially unassigned variables
The following categories of variables are classified as initially unassigned:
- Instance variables of initially unassigned struct variables.
- Output parameters, including the this variable of struct instance
constructors.
- Local variables, except those declared in a catch clause or a
foreach statement.
public static int globalId; //assigned
public class TestClass
{
int Id; //Assigned
public void TestMethod()
{
int methodId; //Not assigned
}
}