C# Quick References
Here you can fin quick examples of code to do many common things. This page contains short explanations and examples and is not intended as a substitute for the course tutorials.
You can also find good examples on the following website:
https://www.w3schools.com/cs/index.php
Printing Text
Writing to the Console
Console.WriteLine("Hello World"); // The next item printed will be on a new line
Console.Write("Hello World"); // The next item printed will be on the same line
Print Text and an Expression
The '+' operator means addition if it is surrounded by integers, but will concatenate (stick) strings and integers together when there is a string on one side.
Console.WriteLine("I have " + (1 + 1) + " eyes.");
Will display "I have 2 eyes.". because the 1 + 1 is in brackets, addition is performed.
Console.WriteLine("I have " + 1 + 1 + " eyes.");
Will display "I have 11 eyes." because it will concatenate the "I have " with the first '1'.
Print Text and a Variable
string name = "John Smith";
int year = 1882;
Console.WriteLine(name + " born in " + year);
Variables
https://www.w3schools.com/cs/cs_variables.php
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false
Declaring a variable
To declare a variable, you must specify a type and a name.
Syntax:
type variableName = value
Example:
int quantity = 5;
double price = 5.99;
string item = "Popsicles";
double totalPrice = price * quantity;
Console.WriteLine("Hello Goliath. The total price is $" + totalPrice);
User Input
https://www.w3schools.com/cs/cs_user_input.php
Use the following method to read input from the user:
string name = Console.ReadLine();
All input read using ReadLine() is returned as a string. If you need a numeric type, it must be converted.
Converting Types
https://www.w3schools.com/cs/cs_type_casting.php
Use the Convert class to convert a string to a numeric type:
String to Integer
string input = Console.ReadLine();
int number = Convert.ToInt32(input);
// Or all at once
int number = Convert.ToInt32(Console.ReadLine());
String to Double
string input = Console.ReadLine();
double price = Convert.ToDouble(input);
// Or all at once
double price = Convert.ToDouble(Console.ReadLine());
Random Numbers
Create a Random object. Only once at the beginning of your program.
Random generator = new Random();
Use the generator and the Next() method to retrieve random numbers meeting specified criteria.
generator.Next(); // generates a random integer from 0 - Maximum Integer Value
generator.Next(number); // generate a random integer from 0 to (number-1)
generator.Next(min, max); // generate a random integer from min to (max-1)
Examples:
int number = generator.Next(100); // a random integer from 0-99 will be generated
int number = generator.Next(10, 100); // a random integer from 10-99 will be generated
If Statements
https://www.w3schools.com/cs/cs_conditions.php
The condition of an if statement must be something that the computer can evaluate to be true or false.
It can be a boolean value, a method that returns true/false, or a conditional statement.
Here are boolean operators:
Equals: ==
Not Equals: !=
Greater than: >
Greater than or Equal to: >=
Less than: <
Less than or equal to: <=
Basic If Statement
if (condition)
{
// Block of code to be run if the condition is true
}
If...Else
Add an optional else clause if you want to run code when the if condition is not true.
if (condition)
{
// Block of code to be run if the condition is true
}
else
{
// Block of code run if the condition is false
}
If...Else If...Else
Add as many else if statements to an if statement if you want one of many possible options to be run. The else is optional.
if (condition)
{
// Block of code to be run if the condition is true
}
else if (condition)
{
// Block of code to be run if the condition is true and previous if..else if were false
}
else
{
// Block of code run if the condition is false
}
Multiple Conditions
You can test more than one condition in a single if statement
And Operator - &&
Use the and '&&' operator if you need to test for more than 1 condition to be true at the same time.
if (condition1 && condition2)
{
// Block of code run if both condition1 and condition2 are true
}
Or Operator - ||
Use the or '||' operator if you need to test for at least 1 of multiple conditions to be true.
if (condition1 || condition2)
{
// Block of code run if either condition1 or condition2 is true
}
Not Operator - !
Use the not '!' operator to make a boolean value equal to its opposite.
if (!condition)
{
// Block of code run if condition is false.
}
Loops
For Loop
https://www.w3schools.com/cs/cs_for_loop.php
A for loop is used when you know how many times you want to run a block of code.
Format:
for(starting value; condition for executing block; increment)
{
// Code block to be repeated
}
Example:
This will print the values from 0 to 4
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
While Loop
The while loop repeats a block of code as long as a condition is true.
while(condition)
{
// Code to be run of condition is true
}
Arrays
https://www.w3schools.com/cs/cs_arrays.php
Store multiple values of the same type without making multiple variables.
Declare an array before you use it:
string[] names;
You may set all values of an array once it has been declared.
names = {"Homer", "Marge", "Bart", "Lisa", "Maggie"};
If you don't know what values you are going to store in the array, you may initialize an empty array and add items later. You must specify a size:
names = new string[5];
This array names contains no values. They will need to be added by index.
Set the Value of an Element
specify the index of the element you want to change.
names[0] = "Mr. Burns"; // makes the first element in names "Mr. Burns"
Retrieve the Value of an Element
Console.WriteLine(names[2]); // Prints the element at index 2
Determine How Man Elements are in an Array
Use the Length property.
Console.WriteLine(names.Length); // Prints out the size of the array
Displaying Currency
In order to format output as currency, you can use the ToString() method to format it. You will pass "C" as an argument to ToString() in order to format it as currency. It will print out a '$' and then the value followed by exactly two decimal places.
double price = 1.5;
Console.WriteLine("The price is " + price.ToString("C"));
This will print out: The price is $1.50