C# Programming Language
Names Matric No
Mumuni Abdullah 180805047
Alibrown Julius 180805033
Olayanju Joseph 180805003
David Olukolatimi 180805026
Adekogbe Oluwadamilare 180805054
Ifeyinwa Iwelunmor 190805511
Idowu-Koya Irewolede 180805064
Olawale Tolulope 180805043
Table of Contents
1. Course Introduction
2. C# Applications & Use Cases
3. C# Language Fundamentals
4. Data Types & Variables
5. Operators in C#
6. Control Flow - Decision Making
7. Switch Statements & Ternary Operator
8. Loops - For and Foreach
9. While Loops & Loop Control
10. Methods Basics
11. Method Overloading & Parameters
12. Arrays Fundamentals
13. Multidimensional Arrays & Collections
14. Classes and Objects Basics
15. Inheritance and Polymorphism
16. Interfaces and Abstract Classes
17. Exception Handling Basics
18. Custom Exceptions and File I/O
19. LINQ Basics
20. Advanced LINQ & Generics
21. File I/O Operations
22. Working with CSV Files
23. Course Summary & Best Practices
1. Course Introduction
What is C#?
C# (pronounced "C-Sharp") is a modern, general-purpose, object-oriented programming language
Developed by Microsoft within its .NET initiative, led by Anders Hejlsberg
Released in 2000 as part of Microsoft's .NET framework
Combines the power of C++ with the simplicity of Visual Basic
Why C# Matters in Today's Tech Landscape:
Versatility: Web development, desktop applications, mobile apps, game development, cloud applications
Industry Adoption: Used by major companies like Microsoft, Stack Overflow, Alibaba
Career Opportunities: High demand for C# developers in enterprise environments
Modern Language Features: Constant evolution with new language features
2. C# Applications & Use Cases
Real-World Applications:
Web Development: [Link] Core
Desktop Applications: WPF, Windows Forms
Game Development: Unity 3D engine
Mobile Development: Xamarin, .NET MAUI
Cloud & Microservices: Azure functions
Enterprise Software: Banking, CRM systems
Hello World Example:
using System;
class Program
{
static void Main()
{
[Link]("Hello, World!");
}
}
Key Components:
using System; - Import namespaces
Main() - Entry point of application
Statements end with semicolons
Case-sensitive language
3. C# Language Fundamentals
Program Structure:
using System; // Import namespace
using [Link];
namespace MyApplication // Namespace declaration
{
class Program // Class declaration
{
static void Main(string[] args) // Entry point
{
// Your code here
}
}
}
Key Syntax Rules:
Case Sensitive: Variable and variable are different
Semicolons Required: Every statement must end with ;
Curly Braces: {} define code blocks
Comments:
Single line: // This is a comment
Multi-line: /* This is a multi-line comment */
XML Documentation: /// <summary>Documentation</summary>
Naming Conventions:
Classes: PascalCase (StudentRecord, BankAccount)
Methods: PascalCase (CalculateTotal(), GetUserName())
Variables: camelCase (firstName, totalAmount)
Constants: UPPER_CASE (MAX_SIZE, PI_VALUE)
4. Data Types & Variables
Value Types (Stack Memory):
int age = 25; // Whole numbers
double price = 19.99; // Decimal numbers
bool isActive = true; // True/false values
char grade = 'A'; // Single characters
Reference Types (Heap Memory):
string name = "John"; // Text data
int[] numbers = {1, 2, 3}; // Arrays
Variable Declaration:
int count = 10; // Explicit typing
var message = "Hello"; // Implicit typing
const double PI = 3.14; // Constants
Best Practices:
Use meaningful names
Choose appropriate types
Initialize before use
5. Operators in C#
Arithmetic Operators:
int a = 10, b = 3;
int sum = a + b; // Addition: 13
int product = a * b; // Multiplication: 30
int remainder = a % b; // Modulus: 1
Comparison Operators:
bool result = x == y; // Equality
bool result = x != y; // Not equal
bool result = x < y; // Less than
Logical Operators:
bool canEnter = isStudent && hasID; // AND
bool discount = isStudent || isSenior; // OR
bool opposite = !isActive; // NOT
Assignment Operators:
number += 5; // Same as: number = number + 5
number *= 2; // Same as: number = number * 2
Increment/Decrement:
counter++; // Add 1 after use
++counter; // Add 1 before use
6. Control Flow - Decision Making
Control flow allows programs to make decisions based on conditions.
Basic If Statement:
if (score >= 90)
[Link]("Grade: A");
If-Else Chain:
if (score >= 90)
[Link]("Grade: A");
else if (score >= 80)
[Link]("Grade: B");
else
[Link]("Grade: F");
Key Points:
Use parentheses for conditions
Curly braces for multiple statements
else if for multiple conditions
Conditions must evaluate to true/false
7. Switch Statements & Ternary Operator
Switch Statement:
Better for multiple exact value comparisons.
switch (grade)
{
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Good!");
break;
default:
[Link]("Try harder!");
break;
}
Modern Switch Expression (C# 8.0+):
string message = grade switch
{
'A' => "Excellent!",
'B' => "Good!",
_ => "Try harder!"
};
Ternary Operator:
Quick inline conditional assignment.
string status = age >= 18 ? "Adult" : "Minor";
When to Use:
Switch: Multiple exact values
Ternary: Simple true/false assignments
8. Loops - For and Foreach
For Loop:
Used when you know the number of iterations.
for (int i = 1; i <= 10; i++)
{
[Link]($"Number: {i}");
}
For Loop with Arrays:
int[] numbers = {2, 4, 6, 8, 10};
for (int i = 0; i < [Link]; i++)
{
[Link]($"Index {i}: {numbers[i]}");
}
Foreach Loop:
Simpler syntax for iterating through collections.
foreach (int number in numbers)
{
[Link]($"Number: {number}");
}
foreach (char character in "Hello")
{
[Link](character);
}
Key Differences:
For: Need index access, specific iterations
Foreach: Simpler, read-only access to elements
9. While Loops & Loop Control
While Loop:
Executes while condition is true.
int count = 1;
while (count <= 5)
{
[Link]($"Count: {count}");
count++;
}
Do-While Loop:
Executes at least once, then checks condition.
int number;
do
{
[Link]("Enter number (0 to exit): ");
number = Convert.ToInt32([Link]());
} while (number != 0);
Loop Control Statements:
for (int i = 1; i <= 10; i++)
{
if (i == 5)
continue; // Skip this iteration
if (i == 8)
break; // Exit loop completely
[Link](i); // Prints: 1,2,3,4,6,7
}
Best Practices:
Avoid infinite loops
Use meaningful loop variables
Consider foreach for collections
10. Methods Basics
What are Methods?
Reusable blocks of code that perform specific tasks.
Method Structure:
[Access] [static] [ReturnType] MethodName([Parameters])
Basic Examples:
// Method with return value
public static int Add(int a, int b)
{
return a + b;
}
// Method without return value
public static void DisplayWelcome()
{
[Link]("Welcome!");
}
// Method with parameters
public static void PrintResult(int result)
{
[Link]($"Result: {result}");
}
Using Methods:
static void Main()
{
DisplayWelcome();
int sum = Add(10, 20);
PrintResult(sum);
}
Benefits:
Code reusability
Better organization
Easier testing and debugging
11. Method Overloading & Parameters
Method Overloading:
Same method name, different parameters.
public static int Multiply(int a, int b)
{
return a * b;
}
public static double Multiply(double a, double b)
{
return a * b;
}
public static int Multiply(int a, int b, int c)
{
return a * b * c;
}
Parameter Passing:
// Pass by value (default)
public static void ModifyValue(int number)
{
number = 100; // Only local copy changed
}
// Pass by reference
public static void ModifyReference(ref int number)
{
number = 100; // Original variable changed
}
// Out parameter
public static void GetValues(out int a, out int b)
{
a = 10;
b = 20;
}
Best Practices:
Use descriptive method names
Keep methods focused on single tasks
Limit parameter count (max 4-5)
12. Arrays Fundamentals
What are Arrays?
Collections that store multiple elements of the same type.
Array Declaration:
int[] numbers = new int[5]; // Size 5, initialized to 0
int[] scores = {85, 92, 78, 96, 88}; // Direct initialization
string[] names = {"Alice", "Bob", "Charlie"};
Key Concepts:
Zero-indexed (first element at index 0)
Fixed size once created
All elements same data type
Length property for size
Working with Arrays:
// Accessing elements
[Link](scores[0]); // First: 85
[Link](scores[[Link] - 1]); // Last: 88
// Modifying elements
scores[2] = 90; // Change third element
Array Iteration:
// Traditional for loop
for (int i = 0; i < [Link]; i++)
{
[Link]($"Score {i}: {scores[i]}");
}
// Foreach loop (simpler)
foreach (string name in names)
{
[Link]($"Hello, {name}!");
}
13. Multidimensional Arrays & Collections
2D Arrays (Matrices):
int[,] matrix = new int[3, 4]; // 3 rows, 4 columns
int[,] numbers = {{1, 2, 3}, {4, 5, 6}};
// Accessing 2D elements
numbers[1, 2] = 10; // Row 1, Column 2
Jagged Arrays:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] {1, 2};
jaggedArray[1] = new int[] {3, 4, 5, 6};
Modern Collections:
using [Link];
// List<T> - Dynamic array
List<string> students = new List<string>();
[Link]("Alice");
[Link]("Alice");
// Dictionary - Key-value pairs
Dictionary<int, string> grades = new Dictionary<int, string>();
[Link](1, "Excellent");
grades[2] = "Good";
// Queue - FIFO (First In, First Out)
Queue<string> line = new Queue<string>();
[Link]("Person1");
string next = [Link]();
// Stack - LIFO (Last In, First Out)
Stack<int> stack = new Stack<int>();
[Link](10);
int top = [Link]();
When to Use:
Array: Fixed size, simple data
List: Dynamic size, frequent changes
Dictionary: Fast key-based lookup
14. Classes and Objects Basics
What are Classes?
Classes are blueprints for creating objects (instances).
Simple Class Definition:
public class Student
{
// Fields (private data)
private string name;
private int age;
// Properties (public access)
public string Name
{
get { return name; }
set { name = value; }
}
// Auto-implemented property
public string Major { get; set; }
// Constructor
public Student(string name, int age)
{
[Link] = name;
[Link] = age;
}
// Method
public void DisplayInfo()
{
[Link]($"Name: {Name}, Age: {age}");
}
}
Using Classes:
Student student1 = new Student("Alice", 20);
[Link] = "Computer Science";
[Link]();
Key OOP Concepts:
Encapsulation: Hide data, expose through properties
Objects: Instances of classes
Constructors: Initialize objects
15. Inheritance and Polymorphism
Inheritance:
Base class shares functionality with derived classes.
// Base class
public class Person
{
protected string name;
protected int age;
public Person(string name, int age)
{
[Link] = name;
[Link] = age;
}
public virtual void Greet()
{
[Link]($"Hello, I'm {name}");
}
}
// Derived class
public class Student : Person
{
private string studentId;
public Student(string name, int age, string id) : base(name, age)
{
[Link] = id;
}
public override void Greet()
{
[Link]($"Hi! I'm {name}, student ID: {studentId}");
}
}
Polymorphism:
Person[] people = {
new Student("Alice", 20, "CS001"),
new Person("Bob", 30)
};
foreach (Person person in people)
{
[Link](); // Calls appropriate version
}
Benefits:
Code reusability through inheritance
Flexibility through polymorphism
Method overriding for specialized behavior
16. Interfaces and Abstract Classes
Interfaces:
Define contracts that classes must implement.
public interface IDrawable
{
void Draw();
double GetArea();
}
public class Circle : IDrawable
{
private double radius;
public Circle(double radius)
{
[Link] = radius;
}
public void Draw()
{
[Link]($"Drawing circle with radius {radius}");
}
public double GetArea()
{
return [Link] * radius * radius;
}
}
Abstract Classes:
Provide partial implementation for derived classes.
public abstract class Animal
{
protected string name;
public Animal(string name)
{
[Link] = name;
}
// Concrete method
public void Sleep()
{
[Link]($"{name} is sleeping");
}
// Abstract method (must be implemented)
public abstract void MakeSound();
}
public class Dog : Animal
{
public Dog(string name) : base(name) { }
public override void MakeSound()
{
[Link]($"{name} says: Woof!");
}
}
Key Differences:
Interface: Pure contract, no implementation
Abstract class: Partial implementation, shared code
17. Exception Handling Basics
What is Exception Handling?
Structured way to handle runtime errors gracefully.
Basic Structure:
try
{
// Code that might fail
int result = 10 / 0; // Will throw exception
}
catch (DivideByZeroException ex)
{
[Link]("Cannot divide by zero!");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
[Link]("Cleanup code here");
}
Common Exception Types:
DivideByZeroException: Division by zero
FormatException: Invalid string format
ArgumentException: Invalid arguments
NullReferenceException: Null object access
Benefits:
Prevents crashes
Provides meaningful error messages
Allows graceful recovery
Improves user experience
18. Custom Exceptions and File I/O
Custom Exceptions:
public class InsufficientFundsException : Exception
{
public decimal Required { get; }
public decimal Available { get; }
public InsufficientFundsException(decimal required, decimal available)
: base($"Need ${required}, have ${available}")
{
Required = required;
Available = available;
}
}
Using Custom Exceptions:
public void Withdraw(decimal amount)
{
if (amount > balance)
throw new InsufficientFundsException(amount, balance);
balance -= amount;
}
Basic File I/O:
// Writing to file
string content = "Hello, World!";
[Link]("[Link]", content);
// Reading from file
string fileContent = [Link]("[Link]");
[Link](fileContent);
// Reading lines
string[] lines = [Link]("[Link]");
foreach (string line in lines)
{
[Link](line);
}
Best Practices:
Use specific exception types
Always include cleanup code
Handle files with using statements
Validate input to prevent exceptions
19. LINQ Basics
What is LINQ?
Powerful query syntax for data manipulation in C#.
using [Link];
List<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Query syntax
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// Method syntax
var oddNumbers = [Link](n => n % 2 != 0);
Common LINQ Methods:
// Filtering
var largeNumbers = [Link](n => n > 5);
// Ordering
var sorted = [Link](n => n);
// Transforming
var squares = [Link](n => n * n);
// Aggregating
int sum = [Link]();
double average = [Link]();
int max = [Link]();
// Checking conditions
bool hasLarge = [Link](n => n > 8);
bool allPositive = [Link](n => n > 0);
Benefits:
Readable query syntax
Works with any collection
Powerful data manipulation
IntelliSense support
20. Advanced LINQ & Generics
LINQ with Custom Objects:
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
}
// Complex LINQ queries
var itEmployees = employees
.Where(emp => [Link] == "IT")
.OrderByDescending(emp => [Link]);
var departmentStats = employees
.GroupBy(emp => [Link])
.Select(group => new {
Department = [Link],
Count = [Link](),
AvgSalary = [Link](emp => [Link])
});
Generics Introduction:
Generic classes provide type safety and reusability.
public class Stack<T>
{
private List<T> items = new List<T>();
public void Push(T item) => [Link](item);
public T Pop() => [Link]([Link] - 1);
}
// Usage
Stack<int> intStack = new Stack<int>();
Stack<string> stringStack = new Stack<string>();
Benefits:
Type safety at compile time
Code reusability without boxing
Better performance and IntelliSense
21. File I/O Operations
Basic File Operations:
// Writing to file
[Link]("[Link]", "Hello World");
// Reading from file
string content = [Link]("[Link]");
// Reading all lines
string[] lines = [Link]("[Link]");
Using StreamWriter/Reader:
// Writing with StreamWriter
using (StreamWriter writer = new StreamWriter("[Link]"))
{
[Link]("Line 1");
[Link]("Line 2");
}
// Reading with StreamReader
using (StreamReader reader = new StreamReader("[Link]"))
{
string line = [Link]();
}
Exception Handling:
try
{
string data = [Link]("[Link]");
}
catch (FileNotFoundException)
{
[Link]("File not found!");
}
Best Practices:
Always use try-catch for file operations
Use 'using' statements for proper disposal
Check if file exists before reading
22. Working with CSV Files
Simple CSV Operations:
// Writing CSV data
string csvContent = "Name,Age,Major\nAlice,20,CS\nBob,19,Math";
[Link]("[Link]", csvContent);
// Reading CSV data
string[] lines = [Link]("[Link]");
foreach (string line in lines)
{
string[] parts = [Link](',');
[Link]($"Name: {parts[0]}, Age: {parts[1]}");
}
CSV with Custom Class:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return $"{Name},{Age}";
}
}
Using StreamWriter for CSV:
using (StreamWriter writer = new StreamWriter("[Link]"))
{
[Link]("Name,Age"); // Header
[Link]("Alice,20");
[Link]("Bob,19");
}
Best Practices:
Always include headers in CSV files
Handle commas in data with quotes
Use try-catch for file operations
23. Course Summary & Best Practices
What We've Covered:
C# Fundamentals: Variables, operators, data types
Control Flow: If-else, switch, loops
Methods: Functions, overloading, parameters
OOP: Classes, inheritance, polymorphism
Advanced: Interfaces, exceptions, LINQ
Collections: Arrays, Lists, Dictionaries
File I/O: Reading and writing data
Modern Features: Generics, delegates, events
Coding Best Practices:
Use meaningful variable names
Follow naming conventions
Handle exceptions properly
Write small, focused methods
Use LINQ for data queries
Leverage generics for type safety
Next Steps:
Practice with real projects
Learn [Link] for web development
Explore Entity Framework for databases
Build a portfolio of applications
Career Opportunities:
Web Development: [Link] Core
Desktop Apps: WPF, WinUI
Mobile: Xamarin, .NET MAUI
Games: Unity Engine
Cloud: Azure Functions
Resources for Further Learning:
Microsoft Documentation
C# Programming Yellow Book
Pluralsight C# Courses
GitHub C# Projects
Stack Overflow Community