C# C# Basics Perfect var

bot .net
bot .net
9,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");
CodeChallenge.cs
string input = "22";

int converted = int.Parse(input);

bool wheelsAreRound = true;

string downcased = "DoNuTs".ToLower();

bool success = (downcased == "donuts");

double total = 0;

1 Answer

Brendan Whiting
MOD
Brendan Whiting
Front 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".

JavaScript, on the other hand, will let you reassign it to a string. JavaScript doesn't have a compiler, everything is evaluated at runtime, and types are associated with values not with variables.

bot .net
bot .net
9,771 Points

Thanks for the answer. I have heard about .net core, and i saw that treehouse dosent have a complete course on it like with .net any plans to do ? i only saw a workshop about this matter.