31
loading...
This website collects cookies to deliver better user experience
At the end of this lesson, you should be able to answer the following:
string
variable can contain values of the string
type.int number;
number
that has the type of int
. This variable can hold integer numbers.What's in a Name?
User-defined names in C# are called identifiers. Identifiers must follow certain rules - for example, they must start with a letter or an underscore (_
). See this page for more information about identifiers.
int number = 50;
Console.WriteLine()
statement.int number = 50;
Console.WriteLine(number);
50
.int
, that value is 0
.= 50
from the program above and run it. The value in the output will be 0
.int number;
Console.WriteLine(number);
number = 5 + 20;
number
variable.5 + 20
into its resulting value.int number = 50;
number = 5 + 20;
Console.WriteLine(number);
25
, you're correct! The program won't display 50
because we assigned a new value to number
in Line 2.string
or bool
value to an int
variable.int number = "Will it blend?"; // This statement will cause an error!
int anotherNumber;
anotherNumber = false; // This statement will ALSO cause an error!
var title = "Full Metal Alchemist";
var
keyword is used to declare variables like title
above. But what is the data type of title
?"Full Metal Alchemist"
to it, which is a string
value, the type of title
is string
. Recall that strings are text values surrounded by double quotes (Lesson 3).var
keyword means we can't declare without an assigned value.var myVariable; // This will cause an error - C# doesn't know what type it is!
Why use the var
keyword at all?
Some types in C# can get really long, like Dictionary<string, string>
and using var
instead of the type name will make our declarations more concise. Read more about the var
keyword here.
Question
What is the output of this program?
var colour = "blue";
colour = "yellow";
Console.WriteLine(colour);
Questions
True or False:
Challenge
Declare three variables with different types: string
, int
, and bool
. Assign either a value or an expression to each variable. Then print each variable using Console.WriteLine()
. Did you get the output you were expecting?