Visual Programming Using C# Notes
Visual Programming Using C# Notes
In this chapter, we will discuss the tools required for creating C# programming. We have
already mentioned that C# is part of .Net framework and is used for writing .Net applications.
Therefore, before discussing the available tools for running a C# program, let us understand
how C# relates to the .Net framework.
It is an object-oriented programming language created by Microsoft that runs on the .NET
Framework.
VISUAL PROGRAMMING |
C# has roots from the C family, and the language is close to other popular languages like
C++ and Java.The first version was released in year 2002. The latest version, C# 8, was
released in September 2019.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
VR
Database applications
VISUAL PROGRAMMING |
Using these tools, you can write all kinds of C# programs from simple command-line
applications to more complex applications. You can also write C# source code files using a
basic text editor, like Notepad, and compile the code into assemblies using the command-line
compiler, which is again a part of the .NET Framework.
VISUAL PROGRAMMING |
Mainly we will be creating Desktop applications so you click as shown below. This is where
you drag and drop your buttons, textboxes, pictures etc.
VISUAL PROGRAMMING |
In this case we just want to create a simple Hello World program so we do as shown below:
Click next and you will be presented with the form shown below.
VISUAL PROGRAMMING |
Click create button as shown above. We want to create a simple program that outputs Hello
World in console mode. Copy and paste the code below:
using System;
namespace HelloWorld
class Program
Console.WriteLine("Hello World!");
VISUAL PROGRAMMING |
The output is shown in console mode below.
Line 1: using System means that we can use classes from the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more
readable.
Line 3: namespace is used to organize your code, and it is a container for classes and other
namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to your program.
Every line of code that runs in C# must be inside a class. In our example, we named the class
Program.
Don't worry if you don't understand how using System, namespace and class works. Just
think of it as something that (almost) always appears in your program, and that you will learn
more about them in a later chapter.
Line 7: Another thing that always appear in a C# program, is the Main method. Any code
inside its curly brackets {} will be executed.
Line 9: Console is a class of the System namespace, which has a WriteLine() method that is
used to output/print text. In our example it will output "Hello World!".
If you omit the using System line, you would have to write System.Console.WriteLine() to
print/output text.
VISUAL PROGRAMMING |
Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.
Note: Unlike Java, the name of the C# file does not have to match the class name, but they
often do (for better organization). When saving the file, save it using a proper name and add
".cs" to the end of the filename.
The basic shell for any code you will write should have the following elements:
using System;
namespace HelloWorld
class Program
// you place the code you want to run inside the main function. Every program begins to
execute from the main function.
WriteLine or Write
The most common method to output something in C# is WriteLine(), but you can also
use Write().
The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add spaces when
needed, for better readability):
Example
Console.WriteLine("Hello World!");
VISUAL PROGRAMMING |
Console.Write("Hello World! ");
Result:
C# Comments
Comments can be used to explain C# code, and to make it more readable. It can also be used
to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//). Any text between // and the end of
the line is ignored by C# (will not be executed). This example uses a single-line comment
before a line of code:
Example
// This is a comment
Console.WriteLine("Hello World!");
C# Multi-line Comments
Multi-line comments start with /* and ends with */. Any text between /* and */ will be
ignored by C#. This example uses a multi-line comment (a comment block) to explain the
code:
Example
Console.WriteLine("Hello World!");
C# Variables
In C#, there are different types of variables (defined with different keywords), for example:
VISUAL PROGRAMMING |
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
To create a variable, you must specify the type and assign it a value:
Syntax
Where type is a C# type (such as int or string), and variableName is the name of the variable
(such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type string and assign it the value "John":
Console.WriteLine(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
Console.WriteLine(myNum);
You can also declare a variable without assigning the value, and assign the value later:
int myNum;
myNum = 15;
Console.WriteLine(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous
value:
VISUAL PROGRAMMING |
Example
Console.WriteLine(myNum);
Constants
However, you can add the const keyword if you don't want others (or yourself) to overwrite
existing values (this will declare the variable as "constant", which means unchangeable and
read-only):
Note: You cannot declare a constant variable without assigning the value. If you do, an error
will occur: A const field requires a value to be provided.
Other Types
int myNum = 5;
Display Variables
The WriteLine() method is often used to display variable values to the console window.
Example
VISUAL PROGRAMMING |
string name = "John";
You can also use the + character to add a variable to another variable:
Example
Console.WriteLine(fullName);
For numeric values, the + character works as a mathematical operator (notice that we
use int (integer) variables here):
int x = 5;
int y = 6;
To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
C# Identifiers
These unique names are called identifiers. Identifiers can be short names (like x and y) or
more descriptive names (age, sum, totalVolume).
VISUAL PROGRAMMING |
Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
// Good
int m = 60;
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter
Names should start with a lowercase letter and it cannot contain whitespace
Names are case sensitive ("myVar" and "myvar" are different variables)
Reserved words (like C# keywords, such as int or double) cannot be used as names
C# Data Types
As explained in the variables chapter, a variable in C# must be a specified data type.
A data type specifies the size and type of variable values. It is important to use the correct
data type for the corresponding variable; to avoid errors, to save time and memory, but it will
also make your code more maintainable and readable. The most common data types are:
VISUAL PROGRAMMING |
string 2 bytes per Stores a sequence of characters, surrounded by double quotes
character
Console.WriteLine(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note
that you should end the value with an "L":
Example
Console.WriteLine(myNum);
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you
should end the value with an "F":
Example
Console.WriteLine(myNum);
VISUAL PROGRAMMING |
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you
can end the value with a "D" (although not required):
Example
Console.WriteLine(myNum);
Booleans
A boolean data type is declared with the bool keyword and can only take the values true or
false:
Example
Characters
The char data type is used to store a single character. The character must be surrounded by
single quotes, like 'A' or 'c':
Example
Console.WriteLine(myGrade);
Strings
The string data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
Console.WriteLine(greeting);
VISUAL PROGRAMMING |
C# Type Casting
Type casting is when you assign a value of one data type to another type.
In C#, there are two types of casting:
Implicit Casting (automatically) - converting a smaller type to a larger type size
char -> int -> long -> float -> double
Explicit Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char
Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
Console.WriteLine(myInt); // Outputs 9
Console.WriteLine(myDouble); // Outputs 9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in front of the
value:
Example
Console.WriteLine(myInt); // Outputs 9
VISUAL PROGRAMMING |
Type Conversion Methods
It is also possible to convert data types explicitly by using built-in methods, such as
Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (int) and
Convert.ToInt64 (long):
Example
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
// Print the value of the variable (userName), which will display the input value
VISUAL PROGRAMMING |
The Console.ReadLine() method returns a string. Therefore, you cannot get information from
another data type, such as int. The following program will cause an error:
Example
Luckily, for you, you just learned from the previous chapter (Type Casting), that you can
convert any type explicitly, by using one of the Convert.To methods:
Example
C# Operators
Operators are used to perform operations on variables and values. In the example below, we
use the + operator to add together two values:
Example
Arithmetic Operators
VISUAL PROGRAMMING |
Operator Name Description Example
C# Assignment Operators
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
int x = 10;
int x = 10;
x += 5;
VISUAL PROGRAMMING |
A list of all assignment operators:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
VISUAL PROGRAMMING |
<<= x <<= 3 x = x << 3
C# Comparison Operators
== Equal to x == y
!= Not equal x != y
C# Logical Operators
Logical operators are used to determine the logic between variables or values:
VISUAL PROGRAMMING |
&& Logical and Returns true if both statements are true x < 5 && x <
10
! Logical not Reverse the result, returns false if the !(x < 5 && x <
result is true 10)
C# Math
The C# Math class has many methods that allows you to perform mathematical tasks on
numbers.
Math.Max(x,y)
The Math.Max(x,y) method can be used to find the highest value of x and y:
Example
Math.Max(5, 10);
Math.Min(x,y)
The Math.Min(x,y) method can be used to find the lowest value of of x and y:
Example
Math.Min(5, 10);
Math.Sqrt(x)
Example
Math.Sqrt(64);
VISUAL PROGRAMMING |
Math.Abs(x)
Example
Math.Abs(-4.7);
Math.Round()
Example
Math.Round(9.99);
C# Strings
Example
String Length
A string in C# is actually an object, which contain properties and methods that can perform
certain operations on strings. For example, the length of a string can be found with
the Length property:
Example
VISUAL PROGRAMMING |
Other Methods
There are many string methods available, for example ToUpper() and ToLower(), which
returns a copy of the string converted to uppercase or lowercase:
Example
String Concatenation
The + operator can be used between strings to combine them. This is called concatenation:
Example
Console.WriteLine(name);
Note that we have added a space after "John" to create a space between firstName and
lastName on print.
You can also use the string.Concat() method to concatenate two strings:
Example
Console.WriteLine(name);
VISUAL PROGRAMMING |
String Interpolation
Example
Console.WriteLine(name);
Also note that you have to use the dollar sign ($) when using the string interpolation method.
Access Strings
You can access the characters in a string by referring to its index number inside square
brackets [].
Example
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
Example
You can also find the index position of a specific character in a string, by using
the IndexOf() method:
Example
VISUAL PROGRAMMING |
Console.WriteLine(myString.IndexOf("e")); // Outputs "1"
Another useful method is Substring(), which extracts the characters from a string, starting
from the specified character position/index, and returns a new string. This method is often
used together with IndexOf() to get the specific character position:
Example
// Full name
Console.WriteLine(lastName);
Special Characters
Because strings must be written within quotes, C# will misunderstand this string, and
generate an error:
string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string
characters:
VISUAL PROGRAMMING |
Escape character Result Description
\\ \ Backslash
Example
string txt = "We are the so-called \"Vikings\" from the north.";
Example
VISUAL PROGRAMMING |
Example
Code Result
\n New Line
\t Tab
\b Backspace
Example
int x = 10;
int y = 20;
Example
string x = "10";
string y = "20";
VISUAL PROGRAMMING |
string z = x + y; // z will be 1020 (a string)
C# Booleans
Very often, in programming, you will need a data type that can only have one of two values,
like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C# has a bool data type, which can take the values true or false.
Boolean Values
A boolean type is declared with the bool keyword and can only take the values true or false:
Example
However, it is more common to return boolean values from boolean expressions, for
conditional testing (see below).
Boolean Expression
You can use a comparison operator, such as the greater than (>) operator to find out if an
expression (or a variable) is true:
Example
int x = 10;
int y = 9;
Or even easier:
VISUAL PROGRAMMING |
Example
In the examples below, we use the equal to (==) operator to evaluate an expression:
Example
int x = 10;
Example
The boolean value of an expression is the basis for all C# comparisons and conditions.
You can use these conditions to perform different actions for different decisions.
The if Statement
Syntax
if (condition)
VISUAL PROGRAMMING |
{
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition
is True, print some text:
Example
Example
int x = 20;
int y = 18;
if (x > y)
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using
the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to
the screen that "x is greater than y".
Use the else statement to specify a block of code to be executed if the condition is False.
Syntax
if (condition)
VISUAL PROGRAMMING |
{
else
}
Example
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
Example explained
In the example above, time (20) is greater than 18, so the condition is False. Because of this,
we move on to the else condition and print to the screen "Good evening". If the time was less
than 18, the program would print "Good day".
Use the else if statement to specify a new condition if the first condition is False.
Syntax
if (condition1)
VISUAL PROGRAMMING |
{
else if (condition2)
else
}
Example
Console.WriteLine("Good morning.");
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
VISUAL PROGRAMMING |
Example explained
In the example above, time (22) is greater than 10, so the first condition is False. The next
condition, in the else if statement, is also False, so we move on to the else condition
since condition1 and condition2 is both False - and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
There is also a short-hand if else, which is known as the ternary operator because it consists
of three operands. It can be used to replace multiple lines of code with a single line. It is often
used to replace simple if else statements:
Syntax
Instead of writing:
Example
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
Example
Console.WriteLine(result);
VISUAL PROGRAMMING |
C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression)
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day)
case 1:
VISUAL PROGRAMMING |
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
This will stop the execution of more code and case testing inside the block.
VISUAL PROGRAMMING |
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of
the code in the switch block.
The default keyword is optional and specifies some code to run if there is no case match:
Example
int day = 4;
switch (day)
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
break;
Loops
Loops are handy because they save time, reduce errors, and they make code more readable.
VISUAL PROGRAMMING |
C# While Loop
The while loop loops through a block of code as long as a specified condition is True:
Syntax
while (condition)
In the example below, the code in the loop will run, over and over again, as long as a variable
(i) is less than 5:
Example
int i = 0;
while (i < 5)
Console.WriteLine(i);
i++;
Note: Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do
VISUAL PROGRAMMING |
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:
Example
int i = 0;
do
Console.WriteLine(i);
i++;
Do not forget to increase the variable used in the condition, otherwise the loop will never
end!
C# For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
Syntax
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
VISUAL PROGRAMMING |
{
Console.WriteLine(i);
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition
is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Another Example
This example will only print even values between 0 and 10:
Example
Console.WriteLine(i);
There is also a foreach loop, which is used exclusively to loop through elements in an array:
Syntax
The following example outputs all elements in the cars array, using a foreach loop:
Example
VISUAL PROGRAMMING |
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(i);
C# Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.
Example
if (i == 4)
break;
Console.WriteLine(i);
C# Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
VISUAL PROGRAMMING |
for (int i = 0; i < 10; i++)
if (i == 4)
continue;
Console.WriteLine(i);
Break Example
int i = 0;
Console.WriteLine(i);
i++;
if (i == 4)
break;
Continue Example
int i = 0;
VISUAL PROGRAMMING |
{
if (i == 4)
i++;
continue;
Console.WriteLine(i);
i++;
Create an Array
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
string[] cars;
To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:
Example
VISUAL PROGRAMMING |
Console.WriteLine(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
Console.WriteLine(cars[0]);
Array Length
To find out how many elements an array has, use the Length property:
Example
Console.WriteLine(cars.Length);
// Outputs 4
You can loop through the array elements with the for loop, and use the Length property to
specify how many times the loop should run.
Example
VISUAL PROGRAMMING |
{
Console.WriteLine(cars[i]);
There is also a foreach loop, which is used exclusively to loop through elements in an array:
Syntax
The following example outputs all elements in the cars array, using a foreach loop:
Example
Console.WriteLine(i);
The example above can be read like this: for each string element (called i - as in index)
in cars, print out the value of i.
If you compare the for loop and foreach loop, you will see that the foreach method is easier to
write, it does not require a counter (using the Length property), and it is more readable.
VISUAL PROGRAMMING |
Sort Arrays
There are many array methods available, for example Sort(), which sorts an array
alphabetically or in an ascending order:
Example
// Sort a string
Array.Sort(cars);
Console.WriteLine(i);
// Sort an int
Array.Sort(myNumbers);
Console.WriteLine(i);
System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in
the System.Linq namespace:
Example
using System;
using System.Linq;
VISUAL PROGRAMMING |
namespace MyApplication
class Program
If you are familiar with C#, you might have seen arrays created with the new keyword, and
perhaps you have seen arrays with a specified size as well. In C#, there are different ways to
create an array:
VISUAL PROGRAMMING |
// Create an array of four elements without specifying the size
// Create an array of four elements, omitting the new keyword, and without specifying the
size
It is up to you which option you choose. In our tutorial, we will often use the last option, as it
is faster and easier to read.
However, you should note that if you declare an array and initialize it later, you have to use
the new keyword:
// Declare an array
string[] cars;
VISUAL PROGRAMMING |
C# Methods
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method is defined with the name of the method, followed by parentheses (). C# provides
some pre-defined methods, which you already are familiar with, such as Main(), but you can
also create your own methods to perform certain actions:
Example
class Program
// code to be executed
Example Explained
Note: In C#, it is good practice to start with an uppercase letter when naming methods, as it
makes the code easier to read.
VISUAL PROGRAMMING |
Call a Method
To call (execute) a method, write the method's name followed by two parentheses () and a
semicolon;
In the following example, MyMethod() is used to print a text (the action), when it is called:
Example
MyMethod();
Example
VISUAL PROGRAMMING |
MyMethod();
MyMethod();
MyMethod();
C# Method Parameters
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the
method.
They are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a method that takes a string called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full
name:
Example
MyMethod("Liam");
MyMethod("Jenny");
VISUAL PROGRAMMING |
MyMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
You can also use a default parameter value, by using the equals sign (=). If we call the
method without an argument, it uses the default value ("Norway"):
Example
Console.WriteLine(country);
MyMethod("Sweden");
MyMethod("India");
MyMethod();
VISUAL PROGRAMMING |
MyMethod("USA");
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter". From the
example above, country is an optional parameter and "Norway" is the default value.
Multiple Parameters
Example
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
VISUAL PROGRAMMING |
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must have the
same number of arguments as there are parameters, and the arguments must be passed in the
same order.
Return Values
The void keyword, used in the examples above, indicates that the method should not return a
value. If you want the method to return a value, you can use a primitive data type (such
as int or double) instead of void, and use the return keyword inside the method:
Example
return 5 + x;
Console.WriteLine(MyMethod(3));
// Outputs 8 (5 + 3)
VISUAL PROGRAMMING |
Example
return x + y;
Console.WriteLine(MyMethod(5, 3));
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
return x + y;
Console.WriteLine(z);
VISUAL PROGRAMMING |
// Outputs 8 (5 + 3)
Named Arguments
Example
Named arguments are especially useful when you have multiple parameters with default
values, and you only want to specify one of them when you call it:
Example
static void MyMethod(string child1 = "Liam", string child2 = "Jenny", string child3 =
"John")
VISUAL PROGRAMMING |
Console.WriteLine(child3);
MyMethod("child3");
// John
C# Method Overloading
Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:
Example
int MyMethod(int x)
float MyMethod(float x)
Consider the following example, which have two methods that add numbers of different type:
Example
return x + y;
return x + y;
VISUAL PROGRAMMING |
}
Instead of defining two methods that should do the same thing, it is better to overload one.
In the example below, we overload the PlusMethod method to work for both int and double:
Example
return x + y;
return x + y;
VISUAL PROGRAMMING |
Console.WriteLine("Double: " + myNum2);
Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.
C# - What is OOP?
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code.
You should extract out the codes that are common for the application, and place them at a
single place and reuse them instead of repeating it.
Classes and objects are the two main aspects of object-oriented programming. Look at the
following illustration to see the difference between class and objects:
CLASS
Fruit
VISUAL PROGRAMMING |
OBJECTS
Apple
Banana
Mango
Another example:
CLASS
Car
OBJECTS
Volvo
Audi
Toyota
So, a class is a template for objects, and an object is an instance of a class. When the
individual objects are created, they inherit all the variables and methods from the class.
You learned from the previous chapter that C# is an object-oriented programming language.
Everything in C# is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Create a Class
VISUAL PROGRAMMING |
To create a class, use the class keyword:
class Car
}
When a variable is declared directly in a class, it is often referred to as a field (or attribute).
It is not required, but it is a good practice to start with an uppercase first letter when naming
classes. Also, it is common that the name of the C# file and the class matches, as it makes our
code organized. However it is not required (like in Java).
Create an Object
An object is created from a class. We have already created the class named Car, so now we
can use this to create objects.
To create an object of Car, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and use it to print the value of color:
class Car
Console.WriteLine(myObj.color);
VISUAL PROGRAMMING |
Note that we use the dot syntax (.) to access variables/fields inside a class (myObj.color).
You will learn more about fields in the next chapter.
Multiple Objects
Example
class Car
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
You can also create an object of a class and access it in another class. This is often used for
better organization of classes (one class has all the fields and methods, while the other class
holds the Main() method (code to be executed)).
prog2.cs
VISUAL PROGRAMMING |
prog.cs
prog2.cs
class Car
}
prog.cs
class Program
Console.WriteLine(myObj.color);
Did you notice the public keyword? It is called an access modifier, which specifies that
the color variable/field of Car is accessible for other classes as well, such as Program.
Class Members
Fields and methods inside classes are often referred to as "Class Members":
Example
Create a Car class with three class members: two fields and one method.
// The class
class MyClass
// Class members
VISUAL PROGRAMMING |
public void fullThrottle() // method
Fields
In the previous chapter, you learned that variables inside a class are called fields, and that you
can access them by creating an object of the class, and by using the dot syntax (.).
The following example will create an object of the Car class, with the name myObj. Then we
print the value of the fields color and maxSpeed:
Example
class Car
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
VISUAL PROGRAMMING |
You can also leave the fields blank, and modify them when creating the object:
Example
class Car
string color;
int maxSpeed;
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
Example
class Car
string model;
string color;
int year;
VISUAL PROGRAMMING |
{
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
Object Methods
You learned from the C# Methods chapter that methods are used to perform certain actions.
Methods normally belongs to a class, and they define how an object of a class behaves.
VISUAL PROGRAMMING |
Just like with fields, you can access methods with the dot syntax. However, note that the
method must be public. And remember that we use the name of the method followed by two
parantheses () and a semicolon ; to call (execute) the method:
Example
class Car
Why did we declare the method as public, and not static, like in the examples from the C#
Methods Chapter?
The reason is simple: a static method can be accessed without creating an object of the class,
while public methods can only be accessed by objects.
Remember from the last chapter, that we can use multiple classes for better organization (one
for fields and methods, and another one for execution). This is recommended:
VISUAL PROGRAMMING |
prog2.cs
class Car
}
prog.cs
class Program
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
VISUAL PROGRAMMING |
Console.WriteLine(Opel.model);
The public keyword is called an access modifier, which specifies that the fields of Car are
accessible for other classes as well, such as Program.
Tip: As you continue to read, you will also learn more about other class members, such
as constructors and properties.
Constructors
Example
Create a constructor:
class Car
public Car()
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
VISUAL PROGRAMMING |
Console.WriteLine(Ford.model); // Print the value of model
// Outputs "Mustang"
Note that the constructor name must match the class name, and it cannot have a return
type (like void or int).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, C#
creates one for you. However, then you are not able to set initial values for fields.
Constructors save time! Take a look at the last example on this page to really understand
why.
Constructor Parameters
The following example adds a string modelName parameter to the constructor. Inside the
constructor we set model to modelName (model=modelName). When we call the constructor,
we pass a parameter to the constructor ("Mustang"), which will set the value
of model to "Mustang":
Example
class Car
model = modelName;
VISUAL PROGRAMMING |
}
Console.WriteLine(Ford.model);
// Outputs "Mustang"
Example
class Car
model = modelName;
color = modelColor;
year = modelYear;
VISUAL PROGRAMMING |
static void Main(string[] args)
Tip: Just like other methods, constructors can be overloaded by using different numbers of
parameters.
When you consider the example from the previous chapter, you will notice that constructors
are very useful, as they help reducing the amount of code:
Without constructor:
class Program
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
VISUAL PROGRAMMING |
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
With constructor:
class Program
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
Access Modifiers
By now, you are quite familiar with the public keyword that appears in many of our
examples:
The public keyword is an access modifier, which is used to set the access level/visibility for
classes, fields, methods and properties.
VISUAL PROGRAMMING |
C# has the following access modifiers:
Modifier Description
protected The code is accessible within the same class, or in a class that is inherited from that
class. You will learn more about inheritance in a later chapter
internal The code is only accessible within its own assembly, but not from another assembly.
You will learn more about this in a later chapter
Private Modifier
If you declare a field with a private access modifier, it can only be accessed within the same
class:
Example
class Car
VISUAL PROGRAMMING |
{
Console.WriteLine(myObj.model);
Mustang
Example
class Car
class Program
Console.WriteLine(myObj.model);
VISUAL PROGRAMMING |
Public Modifier
If you declare a field with a public access modifier, it is accessible for all classes:
Example
class Car
class Program
Console.WriteLine(myObj.model);
Mustang
To control the visibility of class members (the security level of each individual class and
class member).
To achieve "Encapsulation" - which is the process of making sure that "sensitive" data is
hidden from users. This is done by declaring fields as private. You will learn more about this
in the next chapter.
Note: By default, all members of a class are private if you don't specify an access modifier:
Example
VISUAL PROGRAMMING |
class Car
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
Properties
You learned from the previous chapter that private variables can only be accessed within the
same class (an outside class has no access to it). However, sometimes we need to access them
- and it can be done with properties.
A property is like a combination of a variable and a method, and it has two methods:
a get and a set method:
Example
class Person
VISUAL PROGRAMMING |
set { name = value; } // set method
Example explained
The Name property is associated with the name field. It is a good practice to use the same
name for both the property and the private field, but with an uppercase first letter.
The set method assigns a value to the name variable. The value keyword represents the value
we assign to the property.
If you don't fully understand it, take a look at the example below.
Now we can use the Name property to access and update the private field of the Person class:
Example
class Person
class Program
VISUAL PROGRAMMING |
{
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
Liam
C# also provides a way to use short-hand / automatic properties, where you do not have to
define the field for the property, and you only have to write get; and set; inside the property.
The following example will produce the same result as the example above. The only
difference is that there is less code:
Example
class Person
{ get; set; }
VISUAL PROGRAMMING |
class Program
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
Liam
Why Encapsulation?
Better control of class members (reduce the possibility of yourself (or others) to mess
up the code)
Fields can be made read-only (if you only use the get method), or write-only (if you
only use the set method)
Flexible: the programmer can change one part of the code without affecting other
parts
Increased security of data
C# Inheritance
Inheritance (Derived and Base Class)
In C#, it is possible to inherit fields and methods from one class to another. We group the
"inheritance concept" into two categories:
Derived Class (child) - the class that inherits from another class
Base Class (parent) - the class being inherited from
VISUAL PROGRAMMING |
In the example below, the Car class (child) inherits the fields and methods from
the Vehicle class (parent):
Example
Console.WriteLine("Tuut, tuut!");
class Program
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
VISUAL PROGRAMMING |
// Display the value of the brand field (from the Vehicle class) and the value of the
modelName from the Car class
- It is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.
Tip: Also take a look at the next chapter, Polymorphism, which uses inherited methods to
perform different tasks.
If you don't want other classes to inherit from a class, use the sealed keyword:
...
...
VISUAL PROGRAMMING |
C# Polymorphism
Polymorphism and Overriding Methods
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us inherit fields and methods from
another class. Polymorphism uses those methods to perform different tasks. This allows us
to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound().
Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example
VISUAL PROGRAMMING |
public void animalSound()
Remember from the Inheritance chapter that we use the : symbol to inherit from a class.
Now we can create Pig and Dog objects and call the animalSound() method on both of them:
Example
VISUAL PROGRAMMING |
class Dog : Animal // Derived class (child)
class Program
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
VISUAL PROGRAMMING |
Not The Output I Was Looking For
The output from the example above was probably not what you expected. That is because the
base class method overrides the derived class method, when they share the same name.
VISUAL PROGRAMMING |
}
class Program
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
- It is useful for code reusability: reuse fields and methods of an existing class when you
create a new class.
C# Abstraction
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only essential
information to the user.
VISUAL PROGRAMMING |
Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter).
Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the derived class (inherited from).
Console.WriteLine("Zzz");
From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // Will generate an error (Cannot create an instance of the
abstract class or interface 'Animal')
To access the abstract class, it must be inherited from another class. Let's convert the Animal
class we used in the Polymorphism chapter to an abstract class.
Remember from the Inheritance chapter that we use the : symbol to inherit from a class, and
that we use the override keyword to override the base class method.
Example
// Abstract class
VISUAL PROGRAMMING |
{
// Regular method
Console.WriteLine("Zzz");
class Program
VISUAL PROGRAMMING |
}
To achieve security - hide certain details and only show the important details of an object.
Note: Abstraction can also be achieved with Interfaces, which you will learn more about in
the next chapter.
C# Interface
Interfaces
An interface is a completely "abstract class", which can only contain abstract methods and
properties (with empty bodies):
Example
// interface
interface Animal
It is considered good practice to start with the letter "I" at the beginning of an interface, as it
makes it easier for yourself and others to remember that it is an interface and not a class.
Note: Interfaces can contain properties and methods, but not fields.
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class. To implement an interface, use the : symbol (just like with inheritance). The
body of the interface method is provided by the "implement" class. Note that you do not have
to use the override keyword when implementing an interface:
Example
VISUAL PROGRAMMING |
// Interface
interface IAnimal
class Program
myPig.animalSound();
Notes on Interfaces:
VISUAL PROGRAMMING |
Like abstract classes, interfaces cannot be used to create objects (in the example above, it
is not possible to create an "IAnimal" object in the Program class)
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
Interfaces can contain properties and methods, but not fields/variables
Interface members are by default abstract and public
An interface cannot contain a constructor (as it cannot be used to create objects)
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) C# does not support "multiple inheritance" (a class can only inherit from one base class).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces. Note: To implement multiple interfaces, separate them with a comma (see
example below).
Multiple Interfaces
Example
interface IFirstInterface
interface ISecondInterface
VISUAL PROGRAMMING |
public void myMethod()
Console.WriteLine("Some text..");
class Program
myObj.myMethod();
myObj.myOtherMethod();
C# Enum
To create an enum, use the enum keyword (instead of class or interface), and separate the
enum items with a comma:
Example
enum Level
VISUAL PROGRAMMING |
{
Low,
Medium,
High
Console.WriteLine(myVar);
Example
class Program
enum Level
Low,
Medium,
High
Console.WriteLine(myVar);
VISUAL PROGRAMMING |
The output will be:
Medium
Enum Values
By default, the first item of an enum has the value 0. The second has the value 1, and so on.
To get the integer value from an item, you must explicitly convert the item to an int:
Example
enum Months
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
Console.WriteLine(myNum);
You can also assign your own enum values, and the next items will update the number
accordingly:
VISUAL PROGRAMMING |
Example
enum Months
January, // 0
February, // 1
March=6, // 6
April, // 7
May, // 8
June, // 9
July // 10
Console.WriteLine(myNum);
Enums are often used in switch statements to check for corresponding values:
Example
enum Level
Low,
Medium,
VISUAL PROGRAMMING |
High
switch(myVar)
case Level.Low:
Console.WriteLine("Low level");
break;
case Level.Medium:
Console.WriteLine("Medium level");
break;
case Level.High:
Console.WriteLine("High level");
break;
Medium level
C# Files
Working With Files
The File class from the System.IO namespace, allows us to work with files:
Example
VISUAL PROGRAMMING |
using System.IO; // include the System.IO namespace
The File class has many useful methods for creating and getting information about files. For
example:
Method Description
Replace() Replaces the contents of a file with the contents of another file
WriteAllText() Creates a new file and writes the contents to it. If the file already exists,
it will be overwritten.
For a full list of File methods, go to Microsoft .Net File Class Reference.
VISUAL PROGRAMMING |
Write To a File and Read It
In the following example, we use the WriteAllText() method to create a file named
"filename.txt" and write some content to it. Then we use the ReadAllText() method to read
the contents of the file:
Example
Hello World!
C# Exceptions - Try..Catch
C# Exceptions
When executing C# code, different errors can occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable things.
When an error occurs, C# will normally stop and generate an error message. The technical
term for this is: C# will throw an exception (throw an error).
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
VISUAL PROGRAMMING |
Syntax
try
catch (Exception e)
Console.WriteLine(myNumbers[10]); // error!
If an error occurs, we can use try...catch to catch the error and execute some code to handle it.
In the following example, we use the variable inside the catch block (e) together with the
built-in Message property, which outputs a message that describes the exception:
Example
try
Console.WriteLine(myNumbers[10]);
catch (Exception e)
Console.WriteLine(e.Message);
VISUAL PROGRAMMING |
}
Example
try
Console.WriteLine(myNumbers[10]);
catch (Exception e)
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
try
Console.WriteLine(myNumbers[10]);
catch (Exception e)
VISUAL PROGRAMMING |
{
finally
The throw statement is used together with an exception class. There are many exception
classes available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutEx
ception, etc:
Example
else
VISUAL PROGRAMMING |
}
checkAge(15);
Example
checkAge(20);
VISUAL PROGRAMMING |