0% found this document useful (0 votes)
39 views28 pages

Csharp Document

C sharp

Uploaded by

chidiume obi
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)
39 views28 pages

Csharp Document

C sharp

Uploaded by

chidiume obi
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/ 28

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: ASP.NET 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()
{
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:

using System; // Import namespace


using System.Collections.Generic;

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)


Console.WriteLine("Grade: A");

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

7. Switch Statements & Ternary Operator


Switch Statement:
Better for multiple exact value comparisons.

switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good!");
break;
default:
Console.WriteLine("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++)


{
Console.WriteLine($"Number: {i}");
}

For Loop with Arrays:

int[] numbers = {2, 4, 6, 8, 10};


for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Index {i}: {numbers[i]}");
}

Foreach Loop:
Simpler syntax for iterating through collections.

foreach (int number in numbers)


{
Console.WriteLine($"Number: {number}");
}

foreach (char character in "Hello")


{
Console.WriteLine(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)
{
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:

for (int i = 1; i <= 10; i++)


{
if (i == 5)
continue; // Skip this iteration

if (i == 8)
break; // Exit loop completely

Console.WriteLine(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()
{
Console.WriteLine("Welcome!");
}

// Method with parameters


public static void PrintResult(int result)
{
Console.WriteLine($"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
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]}");
}

// Foreach loop (simpler)


foreach (string name in names)
{
Console.WriteLine($"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 System.Collections.Generic;

// List<T> - Dynamic array


List<string> students = new List<string>();
students.Add("Alice");
students.Remove("Alice");

// Dictionary - Key-value pairs


Dictionary<int, string> grades = new Dictionary<int, string>();
grades.Add(1, "Excellent");
grades[2] = "Good";

// Queue - FIFO (First In, First Out)


Queue<string> line = new Queue<string>();
line.Enqueue("Person1");
string next = line.Dequeue();

// Stack - LIFO (Last In, First Out)


Stack<int> stack = new Stack<int>();
stack.Push(10);
int top = stack.Pop();

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)
{
this.name = name;
this.age = age;
}

// Method
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {age}");
}
}

Using Classes:

Student student1 = new Student("Alice", 20);


student1.Major = "Computer Science";
student1.DisplayInfo();

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)


{
this.name = name;
this.age = age;
}

public virtual void Greet()


{
Console.WriteLine($"Hello, I'm {name}");
}
}

// Derived class
public class Student : Person
{
private string studentId;

public Student(string name, int age, string id) : base(name, age)


{
this.studentId = id;
}

public override void Greet()


{
Console.WriteLine($"Hi! I'm {name}, student ID: {studentId}");
}
}

Polymorphism:
Person[] people = {
new Student("Alice", 20, "CS001"),
new Person("Bob", 30)
};

foreach (Person person in people)


{
person.Greet(); // 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)


{
this.radius = radius;
}

public void Draw()


{
Console.WriteLine($"Drawing circle with radius {radius}");
}

public double GetArea()


{
return Math.PI * radius * radius;
}
}

Abstract Classes:
Provide partial implementation for derived classes.
public abstract class Animal
{
protected string name;

public Animal(string name)


{
this.name = name;
}

// Concrete method
public void Sleep()
{
Console.WriteLine($"{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()


{
Console.WriteLine($"{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)
{
Console.WriteLine("Cannot divide by zero!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("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!";
File.WriteAllText("output.txt", content);

// Reading from file


string fileContent = File.ReadAllText("output.txt");
Console.WriteLine(fileContent);

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

19. LINQ Basics


What is LINQ?
Powerful query syntax for data manipulation in C#.

using System.Linq;

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 = numbers.Where(n => n % 2 != 0);

Common LINQ Methods:


// Filtering
var largeNumbers = numbers.Where(n => n > 5);

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

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 => emp.Department == "IT")
.OrderByDescending(emp => emp.Salary);

var departmentStats = employees


.GroupBy(emp => emp.Department)
.Select(group => new {
Department = group.Key,
Count = group.Count(),
AvgSalary = group.Average(emp => emp.Salary)
});

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) => items.Add(item);


public T Pop() => items.RemoveAt(items.Count - 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
File.WriteAllText("data.txt", "Hello World");

// Reading from file


string content = File.ReadAllText("data.txt");

// Reading all lines


string[] lines = File.ReadAllLines("data.txt");

Using StreamWriter/Reader:

// Writing with StreamWriter


using (StreamWriter writer = new StreamWriter("output.txt"))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
}

// Reading with StreamReader


using (StreamReader reader = new StreamReader("input.txt"))
{
string line = reader.ReadLine();
}

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

22. Working with CSV Files


Simple CSV Operations:

// Writing CSV data


string csvContent = "Name,Age,Major\nAlice,20,CS\nBob,19,Math";
File.WriteAllText("students.csv", csvContent);

// Reading CSV data


string[] lines = File.ReadAllLines("students.csv");
foreach (string line in lines)
{
string[] parts = line.Split(',');
Console.WriteLine($"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("output.csv"))
{
writer.WriteLine("Name,Age"); // Header
writer.WriteLine("Alice,20");
writer.WriteLine("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 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

Resources for Further Learning:


Microsoft Documentation
C# Programming Yellow Book
Pluralsight C# Courses
GitHub C# Projects
Stack Overflow Community

You might also like