Introduction to C#
Programming
What is C#?
• An object-oriented programming language created by Microsoft that
runs on the .NET Framework.
• Has roots from the C family, and the language is close to other
popular language like C++ and Java.
• First version was released in year 2002. latest version, C# 11, was
released in November 2022.
History of C#
• Andres Hejlsberg is the key contributor to C# language development.
In 1999, he built a team to develop a new language which was called
“Cool”. The project was approved and announced in July 2000 at
the .Net Developers Conference. The language was later renamed as
C#.
C# is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And more…
Why use C#?
• One of the most popular programming language in the world.
• Easy to learn and simple to use
• It has a huge community support
• Gives a clear structure to programs and allows code to be reused,
lowering development costs.
• C# is close to C, C++ and java, it makes it easy for programmers to
switch to C# or vise versa.
C# IDE
IDE (Integrated Development Environment) is used to edit and compile
code.
C# Syntax
C# Output
• To output values or print text in C#, you can use the WriteLine()
method:
Example:
Console.WriteLine("Hello World!");
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:
• Example:
Console.Write("Hello World! ");
Console.Write("I will print on the same
line.");
C# Comments
• Single-line comments start with two forward slashes ( // ).
C# Comments
• Multi-line comments starts with /* and ends with */
C# Variables
• Variables are containers for storing data values.
C# Identifiers
• All c# variables must be identified with unique names.
• Unique names are called identifiers.
• It can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
C# Data Types
• A data type specifies the size and type of variable values
Declaring Variable
Syntax
type variableName = value;
Example:
Create a variable called name of type string and assign it the value “Layla”
Other examples
String Concatenation
• The + operator can be used between strings to combine them. This is
called concatenation:
Example:
You can also use the
string.Concat() method to
concatenate two strings:
string firstName = “Juan ";
string lastName = "Dela Cruz";
string name = string.Concat(firstName, lastName);
Console.WriteLine(name);
NOTE:
C# uses the + operator for both addition and concatenation.
Remember: Numbers are added. Strings are concatenated.
For numeric values, the + character
works as a mathematical operator
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
Example code for Implicit Casting
Example code for Explicit Casting
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)
• Covert.ToInt64(long)
C# 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.
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:
Console.WriteLine("Enter your age:"); int
age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
Type Conversion Method
• just learned from the previous chapter (Type Casting), that you can
convert any type explicitly, by using one of the Convert. To methods:
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
Exercise #1
Create a C# program will display the following:
• Your Name
• Year and Section
• Age
• Student number
• Favorite quotation
/* discussion ends here…
See you next meeting */
C# Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators - Used to perform
common mathematical operations.
Operator Name Description Example
+ Addition Adds together two values x+y
- subtraction subtracts one value from x –y
another
* multiplication multiplies two value x*y
/ division divides one value by x/y
another
% modulus returns the division x%y
remainder
++ increment increases the value of a x++
variable by 1
-- decrement decreases the value of a x--
variable by 1
example
C# 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.
int x = 5;
int y = 3;
Console.WriteLine(x > y); // returns True because 5 is greater
than 3.
All list of comparison operators:
Operator Name Example
== equal to x == y
!= not equal x != y
> greater than x>y
< less than x<y
>= greater than or equal x >=y
to
<= less than or equal to x <= y
C# 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.
Operator Name Description Example
&& Logical and Returns True if both statements are X < 5 && x < 10
true
|| Logical or Returns True if one of the statements X < 5 || x < 4
is true
! Logical not Reverse the result, returns False if the !(x < 5 && x < 10)
result is true
• Create a C# program that will compare two integers and determine
whether they are equal or not
C# Conditions and If
Statements
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
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
We can also test variables:
The else Statement
• Use the else statement to specify a block of code to be executed if the condition is False.
Syntax:
if (condition)
{
// block of code to be executed if the condition is True
}
else
{
// block of code to be executed if the condition is False
}
Create a C# program
• Create a program that accepts two integers and check whether they
are equal or not.
• Create a C# program that read age of candidate and determine
whether they are eligible to vote or not.
Note: use comparison operator and if else statement
The else if Statement
• Use the else if statement to specify a new condition if the first condition is False.
• Syntax:
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
The else if Statement
• Use the else if statement to specify a new condition if the first condition is False.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is True
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is True
}
else
{
// block of code to be executed if the condition1 is false and condition2 is False
}
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.
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
A break can save a lot of execution time case 3:
because it "ignores" the execution of all the Console.WriteLine("Wednesday");
break;
rest of the code in the switch block. case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
// Outputs "Thursday" (day 4)
The default keyword is optional and specifies
some code to run if there is no case match
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;
}
// Outputs "Looking forward to the Weekend."
Groupings
• Create a food ordering program using switch statement.
/* discussion ends here..
See you next meeting */
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
}
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.
do
{
// code block to be executed
}
while (condition);
int i = 0;
do
{
Console.WriteLine("i=" + i);
i++;
if (i > 5)
break;
}
while(i < 10);
Console.ReadKey();
}
}
}
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
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
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"
// 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) }}
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)
{
// code block to be executed
}
Example
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
Array
• Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
C# Array Declaration
datatype[] arrayName;
Example:
int[] age;
// declare an array
int[] age;
// allocate memory for array
age = new int[5];
int[] age = new int[5];
Array initialization in C#
In C#, we can initialize an array during the declaration. For example,
int [] num = {1, 2, 3, 4, 5};
In an array, we use an index number to
determine the position of each array
element. We can use the index number to
initialize an array in C#. For example,
// declare an array
int[] age = new int[5];
//initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
age[3] = 2;
age[4] = 5;
using System;
namespace Array_Lesson {
class Program {
static void Main(string[] args) {
// create an array
int[] numbers = {1, 2, 3};
//access first element
Console.WriteLine("Element in first index : " + numbers[0]);
//access second element
Console.WriteLine("Element in second index : " + numbers[1]);
//access third element
Console.WriteLine("Element in third index : " + numbers[2]);
Console.ReadLine();
}
}
}
Change Array Elements
using System;
namespace ChangeArray {
class Program {
static void Main(string[] args) {
// create an array
int[] numbers = {1, 2, 3};
Console.WriteLine("Old Value at index 0: " + numbers[0]);
// change the value at index 0
numbers[0] = 11;
//print new value
Console.WriteLine("New Value at index 0: " + numbers[0]);
Console.ReadLine();
}
}
}
Iterating C# Array using Loops
using System;
namespace AccessArrayFor {
class Program {
static void Main(string[] args) {
int[] numbers = { 1, 2, 3};
for(int i=0; i < numbers.Length; i++) {
Console.WriteLine("Element in index " + i + ": " + numbers[i]);
}
Console.ReadLine();
}
}
}
using System;
namespace AccessArrayForeach {
class Program {
static void Main(string[] args) {
int[] numbers = {1, 2, 3};
Console.WriteLine("Array Elements:
");
foreach(int num in numbers) {
Console.WriteLine(num);
}
Console.ReadLine();
}
}
}
C# Array Operations using
System.Linq
• In C#, we have the System.Linq namespace that provides different
methods to perform various operations in an array. For example,
• Example: Find Minimum and Maximum Element
using System;
// provides us various methods to use in an array
using System.Linq;
namespace ArrayMinMax {
class Program {
static void Main(string[] args) {
int[] numbers = {51, 1, 3, 4, 98};
// get the minimum element
Console.WriteLine("Smallest Element: " +
numbers.Min());
// Max() returns the largest number in array
Console.WriteLine("Largest Element: " +
numbers.Max());
Console.ReadLine();
}
}
}
Example: Find the Average of an
Array
using System;
using System.Linq;
namespace ArrayFunction {
class Program {
static void Main(string[] args) {
int[] numbers = {30, 31, 94, 86, 55};
// get the sum of all array elements
float sum = numbers.Sum();
// get the total number of elements present in the array
int count = numbers.Count();
float average = sum/count;
Console.WriteLine("Average : " + average);
// compute the average
Console.WriteLine("Average using Average() : " + numbers.Average());
Console.ReadLine();
}
}
}
Find the error:
using System;
class HelloWorld {
static public void Main () {
Console.Write("Enter size of array: ");
int size=Convert.ToInt32(Console.ReadLine());
int[] arr = new int[size];
Console.Writeline("Enter {0} elements in the array", size);
for (int i = 0; i < size; i++)
{
arr[i]= Convert.ToInt32(Console.ReadLine();
}
Console.Write("\nElements in array are: ");
for (int i = 0; i < size; i++)
{ Console.Write("{0} ", arr[i]); }
Console.ReadLine();
} }
Exercise#2
• Create a C# program to input and print array elements using loop.
• Write a C# program to input elements in array and print all negative
elements.
• Write a C# program to read elements in an array and find the sum of
array elements.
C# program to input and print array elements using loop.
using System;
namespace elements_in_array
{
class Program
{
static void Main(string[] args)
{
//C# program to declare, initialize, input and print array
elements
/* Input array size */
Console.Write("Enter size of array: ");
int size=Convert.ToInt32(Console.ReadLine());
int[] arr = new int[size];
/* Input elements in array */
Console.WriteLine("Enter {0} elements in the array", size);
for (int i = 0; i < size; i++)
{
arr[i]= Convert.ToInt32(Console.ReadLine());
}
/*Print all elements of array*/
Console.Write("\nElements in array are: ");
for (int i = 0; i < size; i++)
{
Console.Write("{0} ", arr[i]);
}
Console.ReadLine();
}
}
/* discussion ends here…
see you next meeting */
Visual Studio
• Microsoft Visual Studio is an integrated development environment
(IDE) from Microsoft.
• It can be used to develop console and graphical user interface
applications along with Windows Forms applications, web sites, web
applications, and web services in both native code together with
managed code for all platforms supported by Microsoft Windows,
Windows Phone, Windows CE, .NET Framework, .NET Compact
Framework and Microsoft Silverlight.
New features VS 2022
• Inclusion of .NET 6 Framework
• Introduces .NET MAUI Technology
• New User Interface
Minimum System Requirement
• 1.8 GHz or faster processor. Quad-core or better recommended.
• 2GB of RAM; 8GB Recommended
• Hard disk minimum of 800MB up to 210 GB.