C# References
Here is a list of common operations and information that you can use for quick reference. This is not a replacement for completing the tutorials in each topic, but just a quick reminder of things you have already learned.
If you think there is something that should be here and is not, let Mr. Aldworth know and he will add it.
Variables and Data Types
String - Stores sequences of characters
string name = "Bob";
Integer - Stores numbers without decimal values
int score = 15;
Double - Stores numbers with decimal values
double price = 2.99;
Boolean - Stores True or False
bool isOver = True;
Rounding Numbers
Use the Round method from the math class to round in a variety of ways.
Official documentation:
Easy to follow tutorial:
double number = 12.456;
Console.WriteLine(Math.Round(number, 2)); //prints 12.46
Displaying Currency
If you wish to display currency, use string interpolation.
OR, you can call the ToString() method when you print out the number:
double price = 1.5;
Console.WriteLine(price.ToString("C");
Numeric Conversions
We will cover two ways to convert strings to various numeric types:
Method 1: Using the Convert class
Converting to an Integer
The convert class makes it easy to convert from any data type to any other. We store integers in a type called Int32. You will have to build your own error checking into your program.
int age;
age = Convert.ToInt32(txtAge.Text); or age = Convert.ToInt32(Console.ReadLine());
This will generate an exception if txtAge.Text (or what the user types in the console) is anything other that an valid integer.
Converting to a Double
double price;
price = Convert.ToDouble(txtPrice.Text); or price = Convert.ToDouble(Console.ReadLine());
This will generate an exception if txtPrice.Text(or what the user types in the console) is anything other that an valid double.
lblOutput.Text = price + ""; //this casts a numeric variable back to a string
Method 2: Using TryParse (has error checking built in)
This method is slightly more difficult to use, but will not crash your program if it fails.
Converting to an Integer
int age;
Int32.TryParse(txtAge.Text, out age);
if TryParse fails, age will be whatever it was before, in this case its default value of zero. TryParse also returns a boolean value of True if it was successful and False if not. We can use this to handle the error.
int age;
if (Int32.TryParse(txtAge.Text, out age)){
//success code if necessary
}
else{
//error code
}
You could also use TryParse as the condition of a while loop in a console program to repeatedly ask the user to enter a valid integer.
while (!Int32.TryParse(Console.ReadLine(), out age))
//error message
Converting to a Double
double price;
Double.TryParse(txtPrice.Text, out price);
if TryParse fails, price will be whatever it was before, in this case its default value of zero. TryParse also returns a boolean value of True if it was successful and False if not. We can use this to handle the error.
double price;
if (Double.TryParse(txtPrice.Text, out price)){
//success code
}
else{
//error code
}
You could also use TryParse as the condition of a while loop in a console program to repeatedly ask the user to enter a valid double.
while (!Double.TryParse(Console.ReadLine(), out age))
//error message
Random Numbers
Step 1 - Constructing a Random object
Random generator = new Random();
If you provide an integer seed, you will generate the same list of random numbers each time you run your program! Good for testing.
Random generator = new Random(seed) ;
Step 2 - Use one of the Next methods to retrieve a random value from your generator
int num;
num = generator.Next(); //Gets a random integer from 0 to Integer.MaxValue
num = generator.Next(max); //Gets a random integer from 0 to max - 1 (max is an integer)
num = generator.Next(min, max); //Gets a random integer from min to max - 1 (min and max are integers)
double num;
num = generator.NextDouble(); //Gets a random double from 0 to 1
num = generator.NextDouble() * 5 //Gets a random double from 0-5
num = generator.NextDouble() * 4 + 1 //Gets a random double from 1-5
Lists
Here is the official documentation for Lists: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8
Declaring a list:
List<type> listName = new List<type>;
List<int> numbers = new List<int>();
List<string> names = new List<string>();
List<double> prices = new List<double>();
# of elements in a list
prices.Count
Printing elements by index:
Console.WriteLine(names[0]); //Prints first element
Console.WriteLine(names[3]); //Prints fourth element
Console.WriteLine(names[Names.Count - 1]); //Prints last element
Add Elements
Add to the end of the list:
numbers.Add(55);
Insert an element at a specific index:
names.Insert(6, "Gary"); //Inserts the name "Gary" at index 6
Remove Elements
Remove by index:
numbers.RemoveAt(5); //Removes the element at index 5
Remove by value:
name.Remove("Gary"); //Removes only the first instance of 'Gary' in the list.
while(name.Remove("Gary")); //Removes ALL instances of 'Gary' in the list.
Looping Through a List
For-Loop using an index (must use if you want to change a value in the list):
for (int i = 0; i < prices.Count; i++){
prices[i] *= 0.5; //Reduces all prices by 50%
Console.WriteLine(prices[i]); //Prints new prices after 50% discount
}
Foreach loop:
foreach (int name in names){
Console.WriteLine(name); //Prints each name
}
Reading From A Text File
There are many ways to read from a file, this covers reading a file line by line.
You must have: using System.IO; at the top of your program
foreach (string line in File.ReadLines(@"filename and path", Encoding.UTF8))
{
Console.WriteLine(line);
}
See WinForms references to get a filename from OpenFileDialog
Writing to a Text File
There are many ways to write to a file, this covers reading a file line by line.
You must have: using System.IO; at the top of your program
1 - Declare a StreamWriter:
StreamWriter writer = new StreamWriter("filename.txt");
2 - Write a line(s) to the file:
writer.WriteLine(word); //You may use a loop if you have a list of items to write to the file.
3 - Once all lines have been written, close the file:
writer.Close();
See WinForms references to get a filename from SaveFileDialog
String Interpolation
Add a $ to a string literal to indicate that variables will be included using interpolation. Put variables or expressions in {} to have them substituted in:
int time = 2
string name = "Polkaroo"
Console.WriteLine($"I saw {name} {time} days ago!");
Formatting Currency
To format a numeric type to display as currency, add :C2 inside the { } where you substitute the variable, OR use ToString("C").
double price = 4.346
Console.WriteLine($"The price is {price:C2}");
//OR
Console.WriteLine($"The price is {price.ToString("C")");
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
}