0% found this document useful (0 votes)
5 views

C# Syntax

This document provides a comprehensive introduction to C# programming, covering fundamental concepts such as syntax, data types, variables, and control structures like loops and conditional statements. It explains how to declare variables, use methods for input and output, and implement basic programming logic. Additionally, it includes examples and best practices for writing clear and maintainable code.

Uploaded by

fabulous Lashid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C# Syntax

This document provides a comprehensive introduction to C# programming, covering fundamental concepts such as syntax, data types, variables, and control structures like loops and conditional statements. It explains how to declare variables, use methods for input and output, and implement basic programming logic. Additionally, it includes examples and best practices for writing clear and maintainable code.

Uploaded by

fabulous Lashid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Syntax

using System;

namespace HelloWorld

class Program

static void Main(string[] args)

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!".

If you omit the using System line, you would have to


write System.Console.WriteLine() to print/output text.

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive; "MyClass" and "myclass" have different meaning.

Note: Unlike Java, the name of the C# file does not have to match the class
name, but they often do (for better organization). When saving the file, save it
using a proper name and add ".cs" to the end of the filename.

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("I am Learning C#");

Console.WriteLine("It is awesome!");

Console.WriteLine(3 + 3);

The Write Method


There is also a Write() method, which is similar to WriteLine().

The only difference is that it does not insert a new line at the end of the output:
Console.Write("Hello World! ");

Console.Write("I will print on the same line.");

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 example uses a single-line comment before a line of code:

// This is a comment

Console.WriteLine("Hello World!");

C# Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by C#.

This example uses a multi-line comment (a comment block) to explain the


code:
/* The code below will print the words Hello World

to the screen, and it is amazing */

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:

• int - stores integers (whole numbers), without decimals, such as 123 or -


123
• double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
• char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
• string - stores text, such as "Hello World". String values are surrounded
by double quotes
• bool - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax

datatype 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.
Example
Create a variable called name of type string and assign it the value "John":

string name = "John";

Console.WriteLine(name);

Example
Create a variable called myNum of type int and assign it the value 15:

int myNum = 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:

int myNum = 15;

myNum = 20; // myNum is now 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:

ExampleGet your own C# Server


const int myNum = 15;

myNum = 20; // error

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.

To combine both text and a variable, use the + character:

ExampleGet your own C# Server


string name = "John";

Console.WriteLine("Hello " + name);

Example
int x = 5;

int y = 6;

Console.WriteLine(x + y); // Print the value of x + y


Declare Many Variables
To declare more than one variable of the same type, use a comma-separated
list:

ExampleGet your own C# Server


int x = 5, y = 6, z = 50;

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.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:

ExampleGet your own C# Server


// Good

int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is


int m = 60;

The general rules for naming variables are:

• 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)

double myDoubleNum = 5.99D; // Floating point number

char myLetter = 'D'; // Character

bool myBool = true; // Boolean

string myText = "Hello"; // String

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:
C# Type Casting
Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

• Implicit Casting (automatically) - converting a smaller type to a larger


type size
char -> int -> long -> float -> double

• Explicit Casting (manually) - converting a larger type to a smaller size


type
double -> float -> long -> int -> char

Implicit Casting
Implicit casting is done automatically when passing a smaller size type to a
larger size type:

Example
int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

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;

int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 9.78

Console.WriteLine(myInt); // Outputs 9

Type Conversion Methods


It is also possible to convert data types explicitly by using built-in methods,
such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32
(int) and Convert.ToInt64 (long):

Example
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


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

ExampleGet your own C# Server


// 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);

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:");

int age = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Your age is: " + age);


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.

C# has the following conditional statements:

• Use if to specify a block of code to be executed, if a specified condition is


true
• Use else to specify a block of code to be executed, if the same condition is
false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

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)

// block of code to be executed if the condition is True

Example
int time = 20;

if (time < 18)

Console.WriteLine("Good day.");

}
else

Console.WriteLine("Good evening.");

// Outputs "Good evening."

Example
int time = 22;

if (time < 10)

Console.WriteLine("Good morning.");

else if (time < 20)

Console.WriteLine("Good day.");

else

Console.WriteLine("Good evening.");

// Outputs "Good evening."


C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.

SyntaxGet your own C# Server


switch(expression)

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

break;

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break and default keywords will be described later in this chapter

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:

Console.WriteLine("Looking forward to the Weekend.");

break;

// Outputs "Thursday" (day 4)

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)

// code block to be executed


}

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++;

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax
do

// code block to be executed

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++;

while (i < 5);

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)

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

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);

You might also like