Learning C#
Learning C#
Learning 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# 12, was
released in November 2023.
C# is used for:
Mobile applications
Desktop applications
Web applications
Web services
Web sites
Games
VR
Database applications
And much, much more!
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.
On the start window, choose Create a new project:
Choose "Console App (.NET Core)" from the list and click on the Next button:
Enter a name for your project, and click on the Create button:
Visual Studio will automatically generate some code for your project:
The code should look something like this:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Hello World!
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.
Run the program by pressing the F5 button on your keyboard (or click on
"Debug" -> "Start Debugging"). This will compile and execute your code. The
result will look something to this:
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:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Hello World!
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.
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. You don't have to
understand the keywords before and after Main. You will get to know them bit
by bit while reading this tutorial.
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!
C# Output
To output values or print text in C#, you can use the WriteLine() method:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Hello World!
You can add as many WriteLine() methods as you want. Note that it will add a new
line for each method:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("I am Learning C#");
Console.WriteLine("It is awesome!");
}
}
}
Hello World!
I am Learning C#
It is awesome!
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(3 + 3);
}
}
}
6
The only difference is that it does not insert a new line at the end of the output:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.Write("Hello World! ");
Console.Write("I will print on the same line.");
}
}
}
Hello World! I will print on the same line.
Note that we add an extra space when needed (after "Hello World!" in the
example above), for better readability.
In this tutorial, we will only use WriteLine() as it makes it easier to read the
output of code.
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).
Example
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// This is a comment
Console.WriteLine("Hello World!");
}
}
}
Hello World!
This example uses a single-line comment at the end of a line of code:
Example
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!"); // This is a comment
}
}
}
Hello World!
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
This example uses a multi-line comment (a comment block) to explain the code:
Example
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
/* The code below will print the words Hello World
to the screen, and it is amazing */
Console.WriteLine("Hello World!");
}
}
}
Hello World!
Hello World!
Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments,
and /* */ for longer.
C# Variables
Variables are containers for storing data values.
In C#, there are different types of variables (defined with different keywords),
for example:
Syntax
type variableName = value;
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string name = "John";
Console.WriteLine(name);
}
}
}
John
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:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum = 15;
Console.WriteLine(myNum);
}
}
}
15
You can also declare a variable without assigning the value, and assign the
value later:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum;
myNum = 15;
Console.WriteLine(myNum);
}
}
}
15
Note that if you assign a new value to an existing variable, it will overwrite the previous
value:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum = 15;
myNum = 20;
Console.WriteLine(myNum);
}
}
}
20
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
Display Variables
The WriteLine() method is often used to display variable values to the console
window.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string name = "John";
Console.WriteLine("Hello " + name);
}
}
}
Hello John
You can also use the + character to add a variable to another variable:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);
}
}
}
John Doe
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 6;
Console.WriteLine(x + y);
}
}
}
11
C# Multiple Variables
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated
list:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
}
}
}
61
You can also assign the same value to multiple variables in one line:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x, y, z;
x = y = z = 50;
Console.WriteLine(x + y + z);
}
}
}
150
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).
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Good
int minutesPerHour = 60;
Console.WriteLine(minutesPerHour);
Console.WriteLine(m);
}
}
}
60
60
Names can contain letters, digits and the underscore character (_)
Names must begin with a letter or underscore
Names should start with a lowercase letter, and 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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum = 5; // integer (whole number)
double myDoubleNum = 5.99D; // floating point number
char myLetter = 'D'; // character
bool myBool = true; // boolean
string myText = "Hello"; // string
Console.WriteLine(myNum);
Console.WriteLine(myDoubleNum);
Console.WriteLine(myLetter);
Console.WriteLine(myBool);
Console.WriteLine(myText);
}
}
}
5
5.99
D
true
Hello
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:
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Floating point types represents numbers with a fractional part, containing one
or more decimals. Valid types are float and double.
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myNum = 100000;
Console.WriteLine(myNum);
}
}
}
100000
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
long myNum = 15000000000L;
Console.WriteLine(myNum);
}
}
}
15000000000
The float and double data types can store fractional numbers. Note that you
should end the value with an "F" for floats and "D" for doubles:
Float Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
float myNum = 5.75F;
Console.WriteLine(myNum);
}
}
}
5.75
Double Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
double myNum = 19.99D;
Console.WriteLine(myNum);
}
}
}
19.99
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);
}
}
}
35000
120000
Booleans
A boolean data type is declared with the bool keyword and can only take the
values true or false:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
}
}
}
True
False
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
char myGrade = 'B';
Console.WriteLine(myGrade);
}
}
}
B
Strings
The string data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello World";
Console.WriteLine(greeting);
}
}
}
Hello World
C# Type Casting
Type casting is when you assign a value of one data type to another type.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Console.WriteLine(myInt);
Console.WriteLine(myDouble);
}
}
}
9
9
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in
front of the value:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
Console.WriteLine(myDouble);
Console.WriteLine(myInt);
}
}
}
9.78
9
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myInt = 10;
double myDouble = 5.25;
bool myBool = true;
Console.WriteLine(Convert.ToString(myInt)); // Convert int to string
Console.WriteLine(Convert.ToDouble(myInt)); // Convert int to double
Console.WriteLine(Convert.ToInt32(myDouble)); // Convert double to int
Console.WriteLine(Convert.ToString(myBool)); // Convert bool to string
}
}
}
10
10
5
True
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.
C# User Input
Get User Input
You have already learned that Console.WriteLine() is used to output (print)
values. Now we will use Console.ReadLine() to get user input.
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// 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
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
}
}
}
Enter username:
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + 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.').
You will learn more about Exceptions and how to handle errors in a later
chapter.
C# Operators
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 100 + 50;
Console.WriteLine(x);
}
}
}
150
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Console.WriteLine(sum1);
Console.WriteLine(sum2);
Console.WriteLine(sum3);
}
}
}
150
400
800
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Example x+y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x + y);
}
}
}
8
Example x-y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x - y);
}
}
}
2
Example x*y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x * y);
}
}
}
15
Example x/y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 12;
int y = 3;
Console.WriteLine(x / y);
}
}
}
4
Example x%y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 2;
Console.WriteLine(x % y);
}
}
}
1
Example x++
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x++;
Console.WriteLine(x);
}
}
}
6
Example x--
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x--;
Console.WriteLine(x);
}
}
}
4
C# Assignment Operator
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
Console.WriteLine(x);
}
}
}
10
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
x += 5;
Console.WriteLine(x);
}
}
}
15
= 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
Example x=5
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(x);
}
}
}
5
Example x+=3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x += 3;
Console.WriteLine(x);
}
}
}
8
Example x-=3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x -= 3;
Console.WriteLine(x);
}
}
}
2
Example x*=3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x *= 3;
Console.WriteLine(x);
}
}
}
15
Example x/=3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
double x = 5;
x /= 3;
Console.WriteLine(x);
}
}
}
1.6666666666666667
Example x%=3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x %= 3;
Console.WriteLine(x);
}
}
}
2
Example x &= 3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x &= 3;
Console.WriteLine(x);
}
}
}
1
Example x |= 3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x |= 3;
Console.WriteLine(x);
}
}
}
7
Example x ^= 3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x ^= 3;
Console.WriteLine(x);
}
}
}
6
Example x >>= 3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x >>= 3;
Console.WriteLine(x);
}
}
}
0
Example x <<= 3
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
x <<= 3;
Console.WriteLine(x);
}
}
}
40
C# Comparison Operators
Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make
decisions.
The return value of a comparison is either True or False. These values are
known as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.
In the following example, we use the greater than operator (>) to find out if 5
is greater than 3:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x > y); // returns True because 5 is greater than 3
}
}
}
True
== Equal to x == y
!= Not equal x != y
Example x == y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x == y); // returns False because 5 is not equal to 3
}
}
}
False
Example x != y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x != y); // returns True because 5 is not equal to 3
}
}
}
True
Example x > y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x > y); // returns True because 5 is greater than 3
}
}
}
True
Example x < y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x < y); // returns False because 5 is not less than 3
}
}
}
False
Example x >= y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x >= y); // returns True because 5 is greater, or equal, to 3
}
}
}
True
Example x <= y
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
int y = 3;
Console.WriteLine(x <= y); // returns False because 5 is neither less than or equal to 3
}
}
}
False
C# Logical Operators
Logical Operators
As with comparison operators, you can also test for True or False values
with logical operators.
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns True if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns False if the result is !(x < 5 && x < 10)
true
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(x > 3 && x < 10); // returns True because 5 is greater than
3 AND 5 is less than 10
}
}
}
True
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(x > 3 || x < 4); // returns True because one of the conditions
are True (5 is greater than 3, but 5 is not less than 4)
}
}
}
True
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 5;
Console.WriteLine(!(x > 3 && x < 10)); // returns False because ! (not) is used
to reverse the result
}
}
}
False
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Max(5, 10));
}
}
}
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Min(5, 10));
}
}
}
5
Math.Sqrt(x)
The Math.Sqrt(x) method returns the square root of x:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Sqrt(64));
}
}
}
8
Math.Abs(x)
The Math.Abs(x) method returns the absolute (positive) value of x:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Abs(-4.7));
}
}
}
4.7
Math.Round()
Math.Round() rounds a number to the nearest whole number:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Math.Round(9.99));
}
}
}
10
C# Strings
C# Strings
Strings are used for storing text.
Example
Create a variable of type string and assign it a value:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello";
Console.WriteLine(greeting);
}
}
}
Hello
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string greeting = "Hello.";
string greeting2 = "Nice to meet you!";
Console.WriteLine(greeting);
Console.WriteLine(greeting2);
}
}
}
Hello.
Nice to meet you!
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine("The length of the txt string is: " + txt.Length);
}
}
}
The length of the txt string is: 26
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "Hello World";
Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD"
Console.WriteLine(txt.ToLower()); // Outputs "hello world"
}
}
}
HELLO WORLD
hello world
C# String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John ";
string lastName = "Doe";
string name = firstName + lastName;
Console.WriteLine(name);
}
}
}
John Doe
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John ";
string lastName = "Doe";
string name = string.Concat(firstName, lastName);
Console.WriteLine(name);
}
}
}
John Doe
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
int y = 20;
int z = x + y;
Console.WriteLine(z);
}
}
}
30
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string x = "10";
string y = "20";
string z = x + y;
Console.WriteLine(z);
}
}
}
1020
C# 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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string firstName = "John";
string lastName = "Doe";
string name = $"My full name is: {firstName} {lastName}";
Console.WriteLine(name);
}
}
}
My full name is: John Doe
Also note that you have to use the dollar sign ( $) when using the string
interpolation method.
String interpolation was introduced in C# version 6.
C# Access Strings
You can access the characters in a string by referring to its index number inside
square brackets [].
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string myString = "Hello";
Console.WriteLine(myString[0]);
}
}
}
H
Note: String indexes start with 0: [0] is the first character. [1] is the second
character, etc.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string myString = "Hello";
Console.WriteLine(myString[1]);
}
}
}
e
You can also find the index position of a specific character in a string, by using
the IndexOf() method:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string myString = "Hello";
Console.WriteLine(myString.IndexOf("e"));
}
}
}
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
using System;
namespace GetLastName
{
class Program
{
static void Main()
{
// Full name
string name = "John Doe";
C# Special Characters
Strings - 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:
\\ \ Backslash
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "We are the so-called \"Vikings\" from the north.";
Console.WriteLine(txt);
}
}
}
We are the so-called "Vikings" from the north.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "It\'s alright.";
Console.WriteLine(txt);
}
}
}
It's alright.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "The character \\ is called backslash.";
Console.WriteLine(txt);
}
}
}
The character \ is called backslash.
Code Result
\n New Line
\t Tab
\b Backspace
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "Hello\nWorld!";
Console.WriteLine(txt);
}
}
}
Hello
World!
Example \t Tab
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "Hello\tWorld!";
Console.WriteLine(txt);
}
}
}
Hello World!
Example Backspace
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string txt = "Hel\blo World!";
Console.WriteLine(txt);
}
}
}
Helo World!
C# Booleans
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
bool isCSharpFun = true;
bool isFishTasty = false;
Console.WriteLine(isCSharpFun); // Outputs True
Console.WriteLine(isFishTasty); // Outputs False
}
}
}
True
False
Boolean Expression
A Boolean expression returns a boolean value: True or False, by comparing
values/variables.
For example, you can use a comparison operator, such as the greater than (>)
operator to find out if an expression (or a variable) is true:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
int y = 9;
Console.WriteLine(x > y); // returns True, because 10 is higher than 9
}
}
}
True
Or even easier:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9
}
}
}
True
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 10;
Console.WriteLine(x == 10); // returns True, because the value of x is equal to 10
}
}
}
True
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(10 == 15); // returns False, because 10 is not equal to 15
}
}
}
False
In the example below, we use the >= comparison operator to find out if the age
(25) is greater than OR equal to the voting age limit, which is set to 18:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myAge = 25;
int votingAge = 18;
Console.WriteLine(myAge >= votingAge); // returns True, meaning 25 year olds are
allowed to vote!
}
}
}
True
Cool, right? An even better approach (since we are on a roll now), would be to
wrap the code above in an if...else statement, so we can perform different
actions depending on the result:
Example
Output "Old enough to vote!" if myAge is greater than or equal to 18.
Otherwise output "Not old enough to vote.":
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int myAge = 25;
int votingAge = 18;
The boolean value of an expression is the basis for all C# comparisons and
conditions.
You will learn more about conditions (if...else) in the next chapter.
C# If ... Else
C# Conditions and If Statements
C# supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
if (20 > 18)
{
Console.WriteLine("20 is greater than 18");
}
}
}
}
20 is greater than 18
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int x = 20;
int y = 18;
if (x > y)
{
Console.WriteLine("x is greater than y");
}
}
}
}
x is greater than y
Example explained
Syntax
if (condition)
else
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}
Good evening.
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."
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}
}
Good evening.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
Console.WriteLine(result);
}
}
}
Good evening.
C# Switch
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
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;
}
}
}
}
Thursday
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.
The default Keyword
The default keyword is optional and specifies some code to run if there is no
case match:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
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;
}
}
}
}
Looking forward to the Weekend.
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
}
}
}
0
1
2
3
4
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
}
}
}
0
1
2
3
4
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!
C# For Loop
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
}
}
}
0
1
2
3
4
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 10; i = i + 2)
{
Console.WriteLine(i);
}
}
}
}
0
2
4
6
8
10
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested
loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Outer loop
for (int i = 1; i <= 2; ++i)
{
Console.WriteLine("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++)
{
Console.WriteLine(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
}
}
}
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
C# Foreach Loop
The foreach Loop
There is also a foreach loop, which is used exclusively to loop through elements
in an array:
Syntax
foreach (type variableName in arrayName)
The following example outputs all elements in the cars array, using
a foreach loop:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}
}
}
Volvo
BMW
Ford
Mazda
Note: Don't worry if you don't understand the example above. You will learn
more about Arrays in the C# Arrays chapter.
C# Break and Continue
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}
Console.WriteLine(i);
}
}
}
}
0
1
2
3
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
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
continue;
}
Console.WriteLine(i);
}
}
}
}
0
1
2
3
5
6
7
8
9
Break Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}
}
}
}
0
1
2
3
Continue Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i < 10)
{
if (i == 4)
{
i++;
continue;
}
Console.WriteLine(i);
i++;
}
}
}
}
0
1
2
3
5
6
7
8
9
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;
To insert values to it, we can use an array literal - place the values in a comma-
separated list, inside curly braces:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars[0]);
}
}
}
Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);
}
}
}
Opel
Array Length
To find out how many elements an array has, use the Length property:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Console.WriteLine(cars.Length);
}
}
}
4
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:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Declare an array
string[] cars;
Console.WriteLine(cars[0]);
}
}
}
Volvo
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}
}
}
}
Volvo
BMW
Ford
Mazda
Syntax
foreach (type variableName in arrayName)
The following example outputs all elements in the cars array, using
a foreach loop:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}
}
}
Volvo
BMW
Ford
Mazda
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.
C# Sort Arrays
Sort an Array
There are many array methods available, for example Sort(), which sorts an
array alphabetically or in an ascending order:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// Sort a string
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Array.Sort(cars);
foreach (string i in cars)
{
Console.WriteLine(i);
}
// Sort an int
int[] myNumbers = {5, 1, 8, 9};
Array.Sort(myNumbers);
foreach (int i in myNumbers)
{
Console.WriteLine(i);
}
}
}
}
BMW
Ford
Mazda
Volvo
1
5
8
9
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
{
static void Main(string[] args)
{
int[] myNumbers = {5, 1, 8, 9};
Console.WriteLine(myNumbers.Max()); // largest value
Console.WriteLine(myNumbers.Min()); // smallest value
Console.WriteLine(myNumbers.Sum()); // sum of myNumbers
}
}
}
9
1
23
C# Multidimensional Arrays
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known
as single dimension arrays. These are great, and something you will use a lot
while programming in C#. However, if you want to store data as a tabular form,
like a table with rows and columns, you need to get familiar
with multidimensional arrays.
Arrays can have any number of dimensions. The most common are two-
dimensional arrays (2D).
Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and
insert a comma (,) inside the square brackets:
Example
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Good to know: The single comma [,] specifies that the array is two-
dimensional. A three-dimensional array would have two commas: int[,,].
numbers is now an array with two arrays as its elements. The first array element
contains three elements: 1, 4 and 2, while the second array element contains 3,
6 and 8. To visualize it, think of the array as a table with rows and columns:
This statement accesses the value of the element in the first row
(0) and third column (2) of the numbers array:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
Console.WriteLine(numbers[0, 2]);
}
}
}
2
Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
The following example will change the value of the element in the first row
(0) and first column (0):
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
numbers[0, 0] = 5;
Console.WriteLine(numbers[0, 0]);
}
}
}
5
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
You can also use a for loop. For multidimensional arrays, you need one loop for
each of the array's dimensions.
Also note that we have to use GetLength() instead of Length to specify how many
times the loop should run:
Example
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
int[,] numbers = { {1, 4, 2}, {3, 6, 8} };
for (int i = 0; i < numbers.GetLength(0); i++)
{
for (int j = 0; j < numbers.GetLength(1); j++)
{
Console.WriteLine(numbers[i, j]);
}
}
}
}
}
1
4
2
3
6
8
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;
In the following example, MyMethod() is used to print a text (the action), when it
is called:
Example
Inside Main(), call the myMethod() method:
using System;
namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
Example
using System;
namespace MyApplication
{
class Program
{
static void MyMethod()
{
Console.WriteLine("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.
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
using System;
namespace MyApplication
{
class Program
{
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
Multiple Parameters
You can have as many parameters as you like, just separate them with
commas:
Example
using System;
namespace MyApplication
{
class Program
{
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
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.
C# Default Parameter Value
Default Parameter Value
You can also use a default parameter value, by using the equals sign ( =).
Example
using System;
namespace MyApplication
{
class Program
{
static void MyMethod(string country = "Norway")
{
Console.WriteLine(country);
}
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
using System;
namespace MyApplication
{
class Program
{
static int MyMethod(int x)
{
return 5 + x;
}
Example
using System;
namespace MyApplication
{
class Program
{
static int MyMethod(int x, int y)
{
return x + y;
}
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
Example
using System;
namespace MyApplication
{
class Program
{
static int MyMethod(int x, int y)
{
return x + y;
}
C# Named Arguments
Named Arguments
It is also possible to send arguments with the key: value syntax.
That way, the order of the arguments does not matter:
Example
using System;
namespace MyApplication
{
class Program
{
static void MyMethod(string child1, string child2, string child3)
{
Console.WriteLine("The youngest child is: " + child3);
}
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
using System;
namespace MyApplication
{
class Program
{
static int PlusMethodInt(int x, int y)
{
return x + y;
}
Instead of defining two methods that should do the same thing, it is better to
overload one.
Example
using System;
namespace MyApplication
{
class Program
{
static int PlusMethod(int x, int y)
{
return x + y;
}
Note: Multiple methods can have the same name as long as the number and/or
type of parameters are different.
C# Classes
C# OOP
C# - What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform
operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.
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.
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:
using System;
namespace MyApplication
{
class Car
{
string color = "red";
Note that we use the dot syntax (.) to access variables/fields inside a class
(myObj.color).
using System;
namespace MyApplication
{
class Car
{
string color = "red";
prog2.cs
prog.cs
prog2.cs
class Car
prog.cs prog2.cs
using System; using System;
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.
You will learn much more about access modifiers and classes/objects in the
next chapters.
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 (.).
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
using System;
namespace MyApplication
{
class Car
{
string color = "red";
int maxSpeed = 200;
You can also leave the fields blank, and modify them when creating the object:
Example
//filename: Car.cs
using System;
namespace MyApplication
{
class Car
{
string color;
int maxSpeed;
Example
//filename: Car.cs
using System;
namespace MyApplication
{
class Car
{
string model;
string color;
int year;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
}
Mustang
Astra
Object Methods
You learned from the C# Methods chapter that methods are used to perform
certain actions.
Methods normally belong 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 parentheses () and a semicolon ; to call (execute) the
method:
Example
using System;
namespace MyApplication
{
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
Why did we declare the method as public, and not static, like in the examples
from the C# Methods Chapter?
prog2.cs
using System;
namespace MyApplication
class Car
{
public string model;
prog.cs
using System;
namespace MyApplication
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);
Mustang
Astra
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.
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
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
using System;
namespace MyApplication
class Person
using System;
namespace MyApplication
class Program
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
Liam
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:
using System;
namespace MyApplication
class Person
{
public string Name // property
get; set;
using System;
namespace MyApplication
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