bot .net9,771 Points
how c# knows that this is a boolean if we use var in this code, and how c# defined as static lanaguge and not dynamic
Hi, I understand that we can use var in order to avoid stating the types but how in this example if i use the keyword "var" C# knows to turn it into a bool? In the other examples like " int converted = int.Parse(input) " c sharp knows to turn into an int because we have the keyword "int" in the right side.
bool success = (downcased == "donuts");
string input = "22"; int converted = int.Parse(input); bool wheelsAreRound = true; string downcased = "DoNuTs".ToLower(); bool success = (downcased == "donuts"); double total = 0;
Brendan WhitingFront End Web Development Treehouse Moderator 82,626 Points
C# can infer the type from what's on the right side of the assignment, even if it doesn't explicitly have the word 'bool'. If you did:
var success = (downcased == "donuts");
The compiler is smart enough to know that the expression
downcased == "donuts" will return a bool, so it knows that when we're defining the variable
success it will be of type
bool. But it won't let it reassign it to something else that isn't a bool later. It won't let you do
success = "hello world".