C# Tutorial
C# Tutorial
C# Tutorial
Tutorial
What is C#?
C# is pronounced "C-Sharp".
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
And much, much more!
C# IDE
The easiest way to get started with C#, is to use an IDE.
In our tutorial, we will use Visual Studio Community, which is free to download
from https://visualstudio.microsoft.com/vs/community/.
C# Install
Once the Visual Studio Installer is downloaded and installed, choose the .NET
workload and click on the Modify/Install button:
After the installation is complete, click on the Launch button to get started with
Visual Studio.
Program.cs
using System;
namespace HelloWorld
class Program
Console.WriteLine("Hello World!");
}
}
Try it Yourself »
Don't worry if you don't understand the code above - we will discuss it in detail
in later chapters. For now, focus on how to run the code.
Hello World!
C:\Users\Username\source\repos\HelloWorld\HelloWorld\bin\Debug\
netcoreapp3.0\HelloWorld.exe (process 13784) exited with code 0.
To automatically close the console when debugging stops, enable
Tools->Options->Debugging->Automatically close the console when
debugging stops.
Press any key to close this window . . .
Congratulations! You have now written and executed your first C# program.
C# Syntax
In the previous chapter, we created a C# file called Program.cs, and we used
the following code to print "Hello World" to the screen:
Program.cs
using System;
namespace HelloWorld
class Program
Console.WriteLine("Hello World!");
Result:
Hello World!
Try it Yourself »
Example explained
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 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.
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. To run the
example above on your computer, make sure that C# is properly installed: Go
to the Get Started Chapter for how to install C#. The output should be:
Hello World!
WriteLine or Write
The most common method to output something in C# is WriteLine(), but you can
also use Write().
Example
Console.WriteLine("Hello World!");
Result:
Hello World!
I will print on a new line.
Hello World! I will print on the same line.
Try it Yourself »
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).
Console.WriteLine("Hello World!");
Try it Yourself »
Example
Console.WriteLine("Hello World!"); // This is a comment
Try it Yourself »
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
Example
/* The code below will print the words Hello World
Console.WriteLine("Hello World!");
Try it Yourself »
C# Variables
Variables are containers for storing data values.
Syntax
type variableName = value;
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);
Try it Yourself »
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);
Try it Yourself »
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
Console.WriteLine(myNum);
Try it Yourself »
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
Change the value of myNum to 20:
Console.WriteLine(myNum);
Try it Yourself »
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):
Example
const int myNum = 15;
The const keyword is useful when you want a variable to always store the same
value, so that others (or yourself) won't mess up your code. An example that is
often referred to as a constant, is PI (3.14159...).
Example
int myNum = 5;
Display Variables
The WriteLine() method is often used to display variable values to the console
window.
Example
string name = "John";
Example
string firstName = "John ";
Console.WriteLine(fullName);
Try it Yourself »
Example
int x = 5;
int y = 6;
Example
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
Try it Yourself »
C# Identifiers
All C# variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
Example
// Good
Try it Yourself »
The general rules for constructing names for variables (unique identifiers) are:
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:
Example
int myNum = 5; // Integer (whole number)
Try it Yourself »
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:
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Numbers
Number types are divided into two groups:
Even though there are many numeric types in C#, the most used for numbers
are int (for whole numbers) and double (for floating point numbers). However,
we will describe them all as you continue to read.
Integer Types
Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.
Example
int myNum = 100000;
Console.WriteLine(myNum);
Try it Yourself »
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
long myNum = 15000000000L;
Console.WriteLine(myNum);
Try it Yourself »
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
float myNum = 5.75F;
Console.WriteLine(myNum);
Try it Yourself »
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
double myNum = 19.99D;
Console.WriteLine(myNum);
Try it Yourself »
Use float or double?
The precision of a floating point value indicates how many digits the value can
have after the decimal point. The precision of float is only six or seven decimal
digits, while double variables have a precision of about 15 digits. Therefore it is
safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate
the power of 10:
Example
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
Try it Yourself »
Booleans
A boolean data type is declared with the bool keyword and can only take the
values true or false:
Example
bool isCSharpFun = true;
Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.
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
char myGrade = 'B';
Console.WriteLine(myGrade);
Try it Yourself »
Strings
The string data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
string greeting = "Hello World";
Console.WriteLine(greeting);
Try it Yourself »
C# Type Casting
Type casting is when you assign a value of one data type to another type.
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
Try it Yourself »
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in
front of the value:
Example
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myInt); // Outputs 9
Try it Yourself »
Example
int myInt = 10;
Try it Yourself »
Why Conversion?
Many times, there's no need for type conversion. But sometimes you have to.
Take a look at the next chapter, when working with user input, to see an
example of this.
In the following example, the user can input his or hers username, which is
stored in the variable userName. Then we print the value of userName:
Example
// Type your username and press enter
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
Run example »
User Input and Numbers
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
Console.WriteLine("Enter your age:");
Like the error message says, you cannot implicitly convert type 'string' to 'int'.
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
Console.WriteLine("Enter your age:");
Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like System.FormatException: 'Input string was not in
a correct format.').
C# Operators
Operators are used to perform operations on variables and values.
Example
int x = 100 + 50;
Try it Yourself »
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Addition
Subtraction
Multiplication
Division
Modulus
Increment
Decrement
C# Assignment Operators
Assignment operators are used to assign values to variables.
Example
int x = 10;
Try it Yourself »
Example
int x = 10;
x += 5;
Try it Yourself »
+= x += 3 x=x+3 Try it »
-= x -= 3 x=x-3 Try it »
*= x *= 3 x=x*3 Try it »
/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »
|= x |= 3 x=x|3 Try it »
^= x ^= 3 x=x^3 Try it »
== Equal to x == y Try it »
&& Logical and Returns true if both statements are true x < 5 && x < 10 Try it »
|| Logical or Returns true if one of the statements is true x < 5 || x < 4 Try it »
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10) Try it »
true
You will learn more about comparison and logical operators in
the Booleans and If...Else chapters.
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);
Try it Yourself »
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);
Try it Yourself »
Math.Sqrt(x)
The Math.Sqrt(x) method returns the square root of x:
Example
Math.Sqrt(64);
Try it Yourself »
Math.Abs(x)
The Math.Abs(x) method returns the absolute (positive) value of x:
Example
Math.Abs(-4.7);
Try it Yourself »
Math.Round()
Math.Round() rounds a number to the nearest whole number:
Example
Math.Round(9.99);
Try it Yourself »
C# Strings
Strings are used for storing text.
Example
Create a variable of type string and assign it a value:
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
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
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 txt = "Hello World";
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
string firstName = "John ";
Console.WriteLine(name);
Run example »
Note that we have added a space after "John" to create a space between
firstName and lastName on print.
Example
string firstName = "John ";
Console.WriteLine(name);
Run example »
String Interpolation
Another option of string concatenation, is string interpolation, which
substitutes values of variables into placeholders in a string. Note that you do
not have to worry about spaces, like with concatenation:
Example
string firstName = "John";
Console.WriteLine(name);
Run example »
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
string myString = "Hello";
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
Example
string myString = "Hello";
You can also find the index position of a specific character in a string, by using
the IndexOf() method:
Example
string myString = "Hello";
Example
// Full name
Run example »
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 backslash (\) escape character turns special characters into string
characters:
\\ \ Backslash
Example
string txt = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Try it Yourself »
Example
string txt = "The character \\ is called backslash.";
Try it Yourself »
\t Tab Try it »
\b Backspace Try it »
Adding Numbers and Strings
WARNING!
Example
int x = 10;
int y = 20;
Example
string x = "10";
string y = "20";
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
bool isCSharpFun = true;
bool isFishTasty = false;
Try it Yourself »
Boolean Expression
A Boolean expression is a C# expression that returns a Boolean
value: True or False.
Example
int x = 10;
int y = 9;
Try it Yourself »
Or even easier:
Example
Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9
Try it Yourself »
Example
int x = 10;
Example
Console.WriteLine(10 == 15); // returns False, because 10 is not equal to
15
Try it Yourself »
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
Use the if statement to specify a block of C# code to be executed if a condition
is True.
Syntax
if (condition)
{
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
if (20 > 18)
Try it Yourself »
int y = 18;
if (x > y)
Try it Yourself »
Example explained
Syntax
if (condition)
else
Example
int time = 20;
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".
Syntax
if (condition1)
}
else if (condition2)
else
Example
int time = 22;
Console.WriteLine("Good morning.");
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
Example explained
However, if the time was 14, our program would print "Good day."
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
Try it Yourself »
Console.WriteLine(result);
Try it Yourself »
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:
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;
Try it Yourself »
The break Keyword
When C# reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
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.
Example
int day = 4;
switch (day)
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
C# While Loop
Loops
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code
more readable.
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++;
}
Try it Yourself »
Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!
Syntax
do
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++;
Try it Yourself »
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
for (statement 1; statement 2; statement 3)
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
for (int i = 0; i < 5; i++)
Console.WriteLine(i);
}
Try it Yourself »
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
for (int i = 0; i <= 10; i = i + 2)
{
Console.WriteLine(i);
Try it Yourself »
Syntax
foreach (type variableName in arrayName)
Console.WriteLine(i);
Try it Yourself »
Note: Don't worry if you don't understand the example above. You will learn
more about Arrays in the C# Arrays chapter.
Example
for (int i = 0; i < 10; i++)
if (i == 4)
break;
Console.WriteLine(i);
Try it Yourself »
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
for (int i = 0; i < 10; i++)
if (i == 4)
continue;
Console.WriteLine(i);
Try it Yourself »
Break Example
int i = 0;
{
Console.WriteLine(i);
i++;
if (i == 4)
break;
Try it Yourself »
Continue Example
int i = 0;
if (i == 4)
{
i++;
continue;
Console.WriteLine(i);
i++;
C# Arrays
Create an Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
string[] cars;
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
// Outputs Volvo
Try it Yourself »
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Example
cars[0] = "Opel";
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
Array Length
To find out how many elements an array has, use the Length property:
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
// Outputs 4
Try it Yourself »
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[i]);
}
Try it Yourself »
Syntax
foreach (type variableName in arrayName)
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
Console.WriteLine(i);
Try it Yourself »
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.
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);
}
Try it Yourself »
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;
namespace MyApplication
class Program
Try it Yourself »
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;
C# Methods
A method is a block of code which only runs when it is called.
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
Create a method inside the Program class:
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.
Call a Method
To call (execute) a method, write the method's name followed by two
parentheses () and a semicolon;
Example
Inside Main(), call the myMethod() method:
MyMethod();
Example
static void MyMethod()
MyMethod();
MyMethod();
MyMethod();
}
// I just got executed!
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.
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Try it Yourself »
Example
static void MyMethod(string country = "Norway")
Console.WriteLine(country);
}
static void Main(string[] args)
MyMethod("Sweden");
MyMethod("India");
MyMethod();
MyMethod("USA");
// Sweden
// India
// Norway
// USA
Try it Yourself »
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
You can have as many parameters as you like:
Example
static void MyMethod(string fname, int age)
MyMethod("Liam", 5);
MyMethod("Jenny", 8);
MyMethod("Anja", 31);
// Liam is 5
// Jenny is 8
// Anja is 31
Try it Yourself »
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
static int MyMethod(int x)
return 5 + x;
}
static void Main(string[] args)
Console.WriteLine(MyMethod(3));
// Outputs 8 (5 + 3)
Try it Yourself »
Example
static int MyMethod(int x, int y)
{
return x + y;
Console.WriteLine(MyMethod(5, 3));
// Outputs 8 (5 + 3)
Try it Yourself »
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
Example
static int MyMethod(int x, int y)
return x + y;
Console.WriteLine(z);
// Outputs 8 (5 + 3)
Try it Yourself »
Named Arguments
It is also possible to send arguments with the key: value syntax.
Example
static void MyMethod(string child1, string child2, string child3)
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")
Console.WriteLine(child3);
MyMethod("child3");
}
// John
Try it Yourself »
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
static int PlusMethodInt(int x, int y)
return x + y;
return x + y;
}
Try it Yourself »
Instead of defining two methods that should do the same thing, it is better to
overload one.
Example
static int PlusMethod(int x, int y)
return x + y;
return x + y;
}
static void Main(string[] args)
Try it Yourself »
Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.
C# OOP
C# - What is OOP?
OOP stands for Object-Oriented Programming.
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.
Look at the following illustration to see the difference between class and
objects:
class
Fruit
objects
Apple
Banana
Mango
Another example:
class
Car
objects
Volvo
Audi
Toyota
When the individual objects are created, they inherit all the variables and
methods from the class.
You will learn much more about classes and objects in the next chapter.
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
To create a class, use the class keyword:
class Car
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);
}
Try it Yourself »
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
You can create multiple objects of one class:
Example
Create two objects of Car:
class Car
Console.WriteLine(myObj1.color);
Console.WriteLine(myObj2.color);
Try it Yourself »
prog2.cs
prog.cs
prog2.cs
class Car
prog.cs
class Program
Console.WriteLine(myObj.color);
}
Try it Yourself »
C# Class Members
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
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 (.).
Example
class Car
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
Try it Yourself »
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);
Try it Yourself »
Example
class Car
{
string model;
string color;
int year;
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);
}
Try it Yourself »
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.
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
}
Try it Yourself »
Why did we declare the method as public, and not static, like in the examples
from the C# Methods Chapter?
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);
Console.WriteLine(Opel.model);
}
Try it Yourself »
Tip: As you continue to read, you will also learn more about other class
members, such as constructors and properties.
C# Constructors
Constructors
A constructor is a special method that is used to initialize objects. The
advantage of a constructor, is that it is called when an object of a class is
created. It can be used to set initial values for fields:
Example
Create a constructor:
public Car()
Car Ford = new Car(); // Create an object of the Car Class (this
will call the constructor)
// Outputs "Mustang"
Try it Yourself »
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
Constructors can also take parameters, which is used to initialize fields.
model = modelName;
Console.WriteLine(Ford.model);
// Outputs "Mustang"
Try it Yourself »
Example
class Car
model = modelName;
color = modelColor;
year = modelYear;
Try it Yourself »
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);
}
Try it Yourself »
With constructor:
prog.cs
class Program
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
C# Access Modifiers
Access Modifiers
By now, you are quite familiar with the public keyword that appears in many of
our examples:
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
Console.WriteLine(myObj.model);
}
Mustang
Try it Yourself »
Example
class Car
class Program
{
static void Main(string[] args)
Console.WriteLine(myObj.model);
Example
class Car
class Program
Console.WriteLine(myObj.model);
Mustang
Try it Yourself »
Example
class Car
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.
Example
class Person
{
get { return name; } // get method
Example explained
If you don't fully understand it, take a look at the example below.
Example
class Person
}
}
class Program
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
Liam
Try it Yourself »
The following example will produce the same result as the example above. The
only difference is that there is less code:
Example
Using automatic properties:
class Person
{ get; set; }
class Program
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
Liam
Try it Yourself »
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:
In the example below, the Car class (child) inherits the fields and methods from
the Vehicle class (parent):
Example
class Vehicle // base class (parent)
Console.WriteLine("Tuut, tuut!");
}
class Car : Vehicle // derived class (child)
class Program
// Call the honk() method (From the Vehicle class) on the myCar
object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and
the value of the modelName from the Car class
}
Run example »
...
}
class Car : Vehicle
...
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.
Example
class Animal // Base class (parent)
}
class Pig : Animal // Derived class (child)
Example
class Animal // Base class (parent)
{
public void animalSound()
class Program
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Try it Yourself »
Example
class Animal // Base class (parent)
{
class Program
{
static void Main(string[] args)
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
Try it Yourself »
C# Abstraction
Abstract Classes and Methods
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which
you will learn more about in the next chapter).
Console.WriteLine("Zzz");
From the example above, it is not possible to create an object of the Animal
class:
Example
// Abstract class
// Regular method
Console.WriteLine("Zzz");
}
}
class Program
}
Try it Yourself »
C# Interface
Interfaces
Another way to achieve abstraction in C#, is with interfaces.
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.
Example
// Interface
interface IAnimal
class Program
myPig.animalSound();
}
Try it Yourself »
Notes on Interfaces:
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
To implement multiple interfaces, separate them with a comma:
Example
interface IFirstInterface
interface ISecondInterface
Console.WriteLine("Some text..");
}
}
class Program
myObj.myMethod();
myObj.myOtherMethod();
Try it Yourself »
C# Enums
An enum is a special "class" that represents a group
of constants (unchangeable/read-only variables).
Example
enum Level
Low,
Medium,
High
Console.WriteLine(myVar);
Try it Yourself »
Example
class Program
enum Level
Low,
Medium,
High
}
Console.WriteLine(myVar);
Medium
Try it Yourself »
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);
Try it Yourself »
You can also assign your own enum values, and the next items will update the
number accordingly:
Example
enum Months
January, // 0
February, // 1
March=6, // 6
April, // 7
May, // 8
June, // 9
July // 10
}
Console.WriteLine(myNum);
Try it Yourself »
Example
enum Level
Low,
Medium,
High
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
Try it Yourself »
C# Files
Working With Files
The File class from the System.IO namespace, allows us to work with files:
Example
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.
Example
using System.IO; // include the System.IO namespace
Hello World!
Run example »
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).
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);
Try it Yourself »
Console.WriteLine(myNumbers[10]);
catch (Exception e)
Try it Yourself »
Finally
The finally statement lets you execute code, after try...catch, regardless of
the result:
Example
try
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
finally
Try it Yourself »
Example
static void checkAge(int age)
else
checkAge(15);
Example
checkAge(20);
Try it Yourself »
Example
int x = 5;
int y = 6;
int sum = x + y;
Try it Yourself »