Csharp Document
Csharp Document
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
Industry Adoption: Used by major companies like Microsoft, Stack Overflow, Alibaba
using System;
class Program
{
static void Main()
{
Console.WriteLine("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:
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)
Variable Declaration:
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:
Logical Operators:
Assignment Operators:
Increment/Decrement:
Basic If Statement:
If-Else Chain:
if (score >= 90)
Console.WriteLine("Grade: A");
else if (score >= 80)
Console.WriteLine("Grade: B");
else
Console.WriteLine("Grade: F");
Key Points:
Use parentheses for conditions
Curly braces for multiple statements
else if for multiple conditions
Conditions must evaluate to true/false
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good!");
break;
default:
Console.WriteLine("Try harder!");
break;
}
Ternary Operator:
Quick inline conditional assignment.
When to Use:
Switch: Multiple exact values
Ternary: Simple true/false assignments
Foreach Loop:
Simpler syntax for iterating through collections.
Key Differences:
For: Need index access, specific iterations
Foreach: Simpler, read-only access to elements
int count = 1;
while (count <= 5)
{
Console.WriteLine($"Count: {count}");
count++;
}
Do-While Loop:
Executes at least once, then checks condition.
int number;
do
{
Console.Write("Enter number (0 to exit): ");
number = Convert.ToInt32(Console.ReadLine());
} while (number != 0);
Loop Control Statements:
if (i == 8)
break; // Exit loop completely
Best Practices:
Avoid infinite loops
Use meaningful loop variables
Consider foreach for collections
Method Structure:
[Access] [static] [ReturnType] MethodName([Parameters])
Basic Examples:
// Method with return value
public static int Add(int a, int b)
{
return a + b;
}
Using Methods:
Benefits:
Code reusability
Better organization
Easier testing and debugging
Parameter Passing:
// 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:
Key Concepts:
Zero-indexed (first element at index 0)
Fixed size once created
All elements same data type
Length property for size
// Accessing elements
Console.WriteLine(scores[0]); // First: 85
Console.WriteLine(scores[scores.Length - 1]); // Last: 88
// Modifying elements
scores[2] = 90; // Change third element
Array Iteration:
// Traditional for loop
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine($"Score {i}: {scores[i]}");
}
// Accessing 2D elements
numbers[1, 2] = 10; // Row 1, Column 2
Jagged Arrays:
Modern Collections:
using System.Collections.Generic;
When to Use:
Array: Fixed size, simple data
List: Dynamic size, frequent changes
Dictionary: Fast key-based lookup
// Auto-implemented property
public string Major { get; set; }
// Constructor
public Student(string name, int age)
{
this.name = name;
this.age = age;
}
// Method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {age}");
}
}
Using Classes:
// Base class
public class Person
{
protected string name;
protected int age;
// Derived class
public class Student : Person
{
private string studentId;
Polymorphism:
Person[] people = {
new Student("Alice", 20, "CS001"),
new Person("Bob", 30)
};
Benefits:
Code reusability through inheritance
Flexibility through polymorphism
Method overriding for specialized behavior
Abstract Classes:
Provide partial implementation for derived classes.
public abstract class Animal
{
protected string name;
// Concrete method
public void Sleep()
{
Console.WriteLine($"{name} is sleeping");
}
Key Differences:
Interface: Pure contract, no implementation
Abstract class: Partial implementation, shared code
Basic Structure:
try
{
// Code that might fail
int result = 10 / 0; // Will throw exception
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Cleanup code here");
}
Benefits:
Prevents crashes
Provides meaningful error messages
Allows graceful recovery
Improves user experience
balance -= amount;
}
// Writing to file
string content = "Hello, World!";
File.WriteAllText("output.txt", content);
// Reading lines
string[] lines = File.ReadAllLines("data.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
Best Practices:
Use specific exception types
Always include cleanup code
Handle files with using statements
Validate input to prevent exceptions
using System.Linq;
// Query syntax
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// Method syntax
var oddNumbers = numbers.Where(n => n % 2 != 0);
// Ordering
var sorted = numbers.OrderByDescending(n => n);
// Transforming
var squares = numbers.Select(n => n * n);
// Aggregating
int sum = numbers.Sum();
double average = numbers.Average();
int max = numbers.Max();
// Checking conditions
bool hasLarge = numbers.Any(n => n > 8);
bool allPositive = numbers.All(n => n > 0);
Benefits:
Readable query syntax
Works with any collection
Powerful data manipulation
IntelliSense support
Generics Introduction:
Generic classes provide type safety and reusability.
// 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
File.WriteAllText("data.txt", "Hello World");
Using StreamWriter/Reader:
Exception Handling:
try
{
string data = File.ReadAllText("file.txt");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found!");
}
Best Practices:
Always use try-catch for file operations
Use 'using' statements for proper disposal
Check if file exists before reading
Best Practices:
Always include headers in CSV files
Handle commas in data with quotes
Use try-catch for file operations
Next Steps:
Practice with real projects
Learn ASP.NET for web development
Explore Entity Framework for databases
Build a portfolio of applications
Career Opportunities:
Web Development: ASP.NET Core
Desktop Apps: WPF, WinUI
Mobile: Xamarin, .NET MAUI
Games: Unity Engine
Cloud: Azure Functions