C# Syntax
C# Syntax
using System;
namespace HelloWorld
class Program
Console.WriteLine("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 3: namespace is used to organize your code, and it is a container for classes
and other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to
your program. Every line of code that runs in C# must be inside a class. In our
example, we named the class Program.
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.
Line 9: Console is a class of the System namespace, which has
a WriteLine() method that is used to output/print text. In our example, it will
output "Hello World!".
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.
C# Output
To output values or print text in C#, you can use the WriteLine() method:
Console.WriteLine("Hello World!");
You can add as many WriteLine() methods as you want. Note that it will add a
new line for each method:
Console.WriteLine("Hello World!");
Console.WriteLine("It is awesome!");
Console.WriteLine(3 + 3);
The only difference is that it does not insert a new line at the end of the output:
Console.Write("Hello World! ");
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).
// This is a comment
Console.WriteLine("Hello World!");
C# Multi-line Comments
Multi-line comments start with /* and ends with */.
Console.WriteLine("Hello World!");
C# Variables
Variables are containers for storing data values.
In C#, there are different data types of variables (defined with different
keywords), for example:
Syntax
Console.WriteLine(name);
Example
Create a variable called myNum of type int and assign it the value 15:
Console.WriteLine(myNum);
You can also declare a variable without assigning the value, and assign the
value later:
Example
int myNum;
myNum = 15;
Console.WriteLine(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Example
Change the value of myNum to 20:
Console.WriteLine(myNum);
Constants
If you don't want others (or yourself) to overwrite existing values, you can add
the const keyword in front of the variable type.
This will declare the variable as "constant", which means unchangeable and
read-only:
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...).
Note: You cannot declare a constant variable without assigning the value. If
you do, an error will occur: A const field requires a value to be provided.
Display Variables
The WriteLine() method is often used to display variable values to the console
window.
Example
int x = 5;
int y = 6;
Console.WriteLine(x + y + z);
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;
Console.WriteLine(x + y + z);
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).
• 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
int myNum = 5; // Integer (whole number)
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:
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
Explicit Casting
Explicit casting must be done manually by placing the type in parentheses in
front of the value:
Example
double myDouble = 9.78;
Console.WriteLine(myInt); // Outputs 9
Example
int myInt = 10;
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
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
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:");
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)
Example
int time = 20;
Console.WriteLine("Good day.");
}
else
Console.WriteLine("Good evening.");
Example
int time = 22;
Console.WriteLine("Good morning.");
Console.WriteLine("Good day.");
else
Console.WriteLine("Good evening.");
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;
default:
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++;
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++;
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);
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
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);