Introduction to C#
Introduction to C# (C-Sharp)
• C# (pronounced "C-sharp") is a modern, object-oriented, and type-safe
programming language developed by Microsoft as part of its .NET platform.
• It’s widely used for building desktop applications, web apps, cloud-based services,
mobile apps, games (using Unity), and more.
Key Features
Constants in C#
Definition: A constant is a fixed value that
cannot be changed once defined.
• Declared using the const keyword.
• Must be initialized at the time of declaration.
Example:
const double Pi = 3.14159;
Variables in C#
• A variable is a named space in memory used to store data.
• C# is strongly typed, meaning the type of a variable must
be defined when declared.
Syntax:
<data_type> variable_name = value;
Example:
int age = 25;
string name = "Alice";
Data Types in C#
Operator in C#
It is a symbol that tells the compiler to perform a specific
operation on one or more values (operands).
Types of operators
Arithmetic Operators
These are used to perform mathematical operations:
Example (a=10,
Operator Meaning Result
b=3)
+ Addition a+b 13
- Subtraction a-b 7
* Multiplication a*b 30
/ Division a/b 3
Modulus
% a%b 1
(remainder)
Relational / Comparison Operators
These are used to compare two values and return true or false:
Example
Operator Meaning Result
(a=10, b=3)
== Equal to a == b false
!= Not equal to a != b true
> Greater than a>b true
< Less than a<b false
Greater than or
>= a >= b true
equal to
Less than or equal
<= a <= b false
to
Logical Operators:-Used to combine multiple
conditions
Operator Meaning Example
(a > 5 && b < 5) →
&& Logical AND
true
` `
! Logical NOT !(a > 5) → false
Assignment Operators:-Used to assign values
Operator Example Same as
= a = 10
+= a += 5 a=a+5
-= a -= 2 a=a-2
*= a *= 3 a=a*3
/= a /= 2 a=a/2
%= a %= 4 a=a%4
Increment and Decrement Operators
Operator Meaning Example Result
++ Increment by 1 a++ or ++a increases a by 1
-- Decrement by 1 a-- or --a decreases a by 1
Type Casting
Changing a value from one data type to another.
Like turning an int into a double, or a double into an int.
1️⃣ Implicit casting (automatic)
•C# does it by itself.
•Safe → no data loss.
•Happens when changing small type → bigger type.
Example:
int num = 10;
double bigNum = num; // automatic
Console.WriteLine(bigNum); // Output: 10
Explicit casting (manual)
•You must do it yourself.
•Needed when changing big type → smaller type.
•May lose data.
Example:
double value = 9.8;
int intValue = (int)value; // manual cast
Console.WriteLine(intValue); // Output: 9
Using Convert
•C# provides helper methods to safely change types.
Example:
string text = "123";
int number = Convert.ToInt32(text);
Console.WriteLine(number); // Output: 123
Control flow statements
They help you decide what to do, when to do it, and how
many times to do it in your program.
Think of them like traffic signals:
Green → go (do something)
Red → stop
Yellow → maybe do something else
Conditional statements
Used to make decisions based on conditions.
if statement
Do something only if the condition is true.
int age = 20;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
if...else statement
Do one thing if true, do another if false.
int age = 15;
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
switch statement
Better when you have many fixed choices.
int day = 2;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Other day");
break;}
Loop statements:-Used to repeat something multiple times.
for loop:-Use when you know how many times to repeat.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i); // prints 1 2 3 4 5
}
while loop
Use when you don’t know how many times,
but need to keep repeating while condition is true.
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
do...while loop
Similar to while, but always runs at least once.
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 5);
Array
An array is like a container with numbered slots where you can store
many values of the same type.
For example: a list of numbers, names, or marks.
Example of a simple array:
int[] numbers = { 10, 20, 30, 40 };
This array can hold 4 integers.
We can access them by index: numbers[0] is 10.
Types of arrays in C#:
1️⃣ Single-Dimensional Array (1D array):-Like a single row or list.
string[] fruits = { "Apple", "Banana", "Mango"};
Console.WriteLine(fruits[1]);
// Output: Banana
2️⃣ Multi-Dimensional Array:-Has more than one row or column.
a) Rectangular Array Like a table with fixed rows and columns.
int[,] matrix = { {1, 2}, {3, 4}, {5, 6} };
// matrix[0,1] is 2
Delegates
1. A delegate is like a pointer to a method.
2. It can hold the reference of a method and call it later.
3. Think of it like: “A remote control (delegate) that can call different TVs (methods) as long as
they have the same signal type (signature).”
4. Pointwise explanation:
1️⃣Delegate stores a method using address of a method.
2️⃣ Must match method signature(same return type and parameters )
3️⃣ Useful for callbacks & events
Delegates help us call methods dynamically.
// Step 1: Define a delegate
delegate void GreetDelegate(string name);
// Step 2: Create methods that match the delegate signature
void SayHello(string name){
Console.WriteLine("Hello, " + name);}
void SayWelcome(string name){
Console.WriteLine("Welcome, " + name);
}
// Step 3: Use the delegate
GreetDelegate greet = SayHello; // store method in delegate
greet("Alice"); // Output: Hello, Alice
greet = SayWelcome; // change to another method
greet("Bob"); // Output: Welcome, Bob
Methods
•A method is a block of code that performs a
specific task
•Helps organize and reuse code
•Improves readability and maintainability
Method Structure
returnType MethodName(parameters)
{ // Code to execute }
•returnType: Type of value returned (use void if none)
•MethodName: Identifier for the method
•parameters: Inputs to the method (optional)
Example of a Simple Method
void SayHello()
{
Console.WriteLine("Hello!");
}
•Does not return any value (void)
•Prints “Hello!” to the console
Method with Parameters and Return Type
int AddNumbers(int a, int b)
{
return a + b;
}
Takes two integers as input
Returns their sum as an integer
Calling a Method
int result = AddNumbers(5, 3); // result = 8
Call the method by passing arguments and Store the returned value in a variable
Method Overloading
Method Overloading means creating multiple methods in
the same class with the same name but different
parameters (different type, number, or order).
It allows methods to perform similar tasks but with
different inputs.
It improves code readability and flexibility.
Example of Method Overloading
Calculator calc = new Calculator();
int sum1 = calc.Add(2, 3); // Calls Add(int, int)
int sum2 = calc.Add(1, 2, 3); // Calls Add(int, int, int)
double sum3 = calc.Add(2.5, 3.5); // Calls Add(double, double)
Object based Manipulation
1.String Object in C#
➢A string is a sequence of characters (letters, numbers, symbols) stored as
a single object.
➢Strings are immutable, meaning once created, they cannot be changed
directly.
➢Example:
string greeting = "Hello, world!";
Console.WriteLine(greeting);
➢Here, "Hello, world!" is a string object stored in the variable greeting.
•Strings are objects of the System.String class.
•They have many useful methods like:
•.Length (gets the number of characters)
•.ToUpper() (converts to uppercase)
•.Substring() (extracts part of the string)
•.Replace() (replaces characters or words)
2.Array Type
•The array type is based on the type of elements it holds.
•Example:
•int[] is an array of integers.
•string[] is an array of strings.
•double[] is an array of doubles.
Syntax to declare an array:
csharp
int[] numbers = new int[5]; // Array of 5 integers
Array Members
Member Description Example Usage
Gets the number of elements in
.Length numbers.Length
the array
.GetValue(i) Returns the value at index i numbers.GetValue(2)
.SetValue(val, i) Sets the value val at index i numbers.SetValue(10, 1)
Copies the array to another array
.CopyTo(array, index) numbers.CopyTo(newArray, 0)
starting at index
Creates a shallow copy of the
.Clone() var copy = numbers.Clone();
array
DateTime Types
•DateTime is a data type in C# used to work with dates and times.
•It can store:
•Date (like 2nd July 2025)
•Time (like 3:30 PM)
•Or both together (like 2nd July 2025, 3:30 PM)
Example:
DateTime now = DateTime.Now; // Current date and time
DateTime today = DateTime.Today;
// Today's date with time set to 00:00:00
DateTime Members
Member What it does Example
.Now Current date and time DateTime now = DateTime.Now;
Current date with time part as
.Today DateTime today = DateTime.Today;
midnight
.AddDays(n) Add or subtract days now.AddDays(5)
.AddHours(n) Add or subtract hours now.AddHours(-2)
.Day, .Month, .Year Gets parts of the date now.Day
.ToString() Converts to string in readable format now.ToString("dd/MM/yyyy")
TimeSpan type
•TimeSpan represents a duration or time interval (not a date).
•Used to store differences between two dates or specific lengths of
time.
Example:
TimeSpan duration = new TimeSpan(2, 30, 0);
// 2 hours, 30 minutes, 0 seconds
Console.WriteLine(duration);
// Output: 02:30:00
Member What it does Example
.Hours, .Minutes,
Gets parts of the TimeSpan duration.Hours
.Seconds
.TotalDays, .TotalHours Gets total value as double duration.TotalMinutes
.Add() Add two TimeSpans duration.Add(TimeSpan.FromMinutes(15))
.Subtract() Subtract TimeSpans duration.Subtract(TimeSpan.FromMinutes(10))