Fall 2020
August 25, 2020
Console.Write and Console.WriteLine.Numeric
sbyte, short, int, long)byte, ushort, uint, ulong)float, double, decimal)Logical (bool)
Character (char)
string)object)(In italics, the one we will mainly be using.)
Integers are “whole” numbers (ℤ = {…, − 1, 0, 1, 2, 3, …}), floating point numbers are real numbers (ℝ), strings are “text messages”, …
Please refer to the “Datatypes in C#” cheatsheet for more information about datatypes.
Literals are fixed values (“Hi Mom”, 40, 1.2404, …) in the source code.
using System;
class MyFirstVariables{
static void Main(){
// Declaration
int myAge;
string myName;
// Assignemnt
myAge = 40;
myName = "Clément";
// Displaying
Console.WriteLine($"I am {myAge} old and my name is {myName}.");
}
}A variable has a name (which must be an identifier), a type, a size, and a value.
| Variable Name | Variable Type | Variable Size | Variable Value |
|---|---|---|---|
myAge |
int |
32 bit | 40 |
myName |
string |
Variable1 | "Clément" |
You can declare and assign a variable in one statement using what is called an “initialization statement”.
There is now one additional rule when it comes to chosing a valid identifier for your variable name: you can not take an identifier that was already used. That is, you can have only one variable named myMessage: if you want to re-assign a variable, you can not use an initialization again (that would re-declare the variable), you need to use an assignment statement again.
The value can change (hence the name!) if you re-assign it. The previously stored value is simply wiped out, and lost.
You can store one variable’s value into another, but that value in the other variable won’t change when the original variable’s value changes:
We can perform basic math operations with numeric datatypes: + (sum), * (multiplication), - (substraction) but also the modulo operation (%), which corresponds to the remainder. More details will be given in lab #3, in homework #2, and during lecture #4.
There is a difference between
int sum = num * 2; // The value of sum is num's value times two
Console.WriteLine($"{sum}"); // The value of sum is displayed.and
You can combine multiple declarations, initializations, and even mix both in one statement:
It’s actually 20 + (n/2) * 4 bytes, for n the number of characters in the string, so 7 in that case.↩︎