Variables

In C#, variables are used to store data that can change while the program is running. Variables have a specific data type that determines the size and type of stored information.

Data types

Variables have a specific data type that determines the size, kind of stored information, and how it can be processed. This course will cover the following data types:
  • string – text strings, for example, "Hello, world!"
  • int – integers, for example, -2, 0, 42
  • bool – Boolean or logical values, true or false

Declaring variables

To declare a variable in C#, you need to specify the data type, the variable name, and assign it an initial value. The syntax looks like this:
Line 1, Char 1

Reading variables

After declaring a variable, you can get its value:
Line 1, Char 1

Changing variables

You can also change the value:
Line 1, Char 1

Outputting variables to the console

You can output not only strings to the console, but all kinds of variables as well. They will automatically be converted to a string.
Line 1, Char 1

Interpolation

String interpolation lets you include variable values and expression results directly in a string. To use string interpolation, put the $ symbol before the string, and place variables and expressions inside curly braces {}:
Line 1, Char 1

Exercises

  1. Declare a Boolean variable named hasJob and print its value. Then change its value and print the updated value.
Line 1, Char 1
  1. Declare a numeric variable named year, assign it the current year, and print it. What year will it be in 5 years? Change the variable and print that value. What about in 10 years?
Line 1, Char 1
  1. What is your favorite movie? Create variables name (title), year (release year), and isComedy (whether it is a comedy) of the appropriate types and assign them values for that movie. Print this information using interpolation. The output might look like this:
Line 1, Char 1