Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,735 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.