Assigning & Reassigning — The Value of a Variable
string lastName;
lastName = "Bordner";
Console.WriteLine("This is the first attempt: " + lastName);
lastName = "Bordner1";
Console.WriteLine("This is the second attempt: " + lastName);
lastName="Bordner";
Console.WriteLine("This is the third attempt: " + lastName);
As demonstrated above, variables can be assigned values.
These values can then be reassigned, new values.
However, this code also demonstrates the value being “reassigned” back to its original value.
“To avoid the possibility of an unassigned local variable, it is recommended that you set the value as soon as possible after you declare it.”
Initializing The Variable
To avoid the error possibility of unassigning a local variable, a variable can be initialized. Initialization occurs when variable declaration and value assignment occur in one line of code.
string lastName = "Bordner";
Console.WriteLine("My last name is: " + lastName);
Implicitly Typed Local Variables
The C# compiler can infer the variable’s data type by the value utilized when the variable is initialized.
An implicitly typed local variable is created using the var keyword. The var keyword lets the C# compiler know that the data type will be implied based on the assigned value.
var lastName = "Bordner";
The var keyword will understand the assigned value in this context to be a string. From this point forward, the variable lastName will be of the string type, and will be limited to interacting as a string data type in the C# code.
“The type is locked in at the time of declaration and therefore will never be able to hold values of a different data type.”
Common Uses of Var Type
(1) Useful when planning the code for an application, as you may not know what data type to use. Using var can help develop the solution.
Leave a Reply