Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Basics (Retired) Perfect var

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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Brendan Whiting
Front End Web Development Techdegree Graduate 84,703 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.

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.