0% found this document useful (0 votes)
3 views14 pages

CSharp OOP2 Topics Codes Examples

This document serves as a teaching handout on core C# OOP concepts, including arrays, loops, classes, inheritance, encapsulation, and polymorphism, with accompanying code examples. It covers essential topics such as constructors, access modifiers, and method overloading/overriding, providing practical illustrations for each concept. Additionally, it includes a combined mini project to demonstrate the integration of these concepts in a real-world scenario.

Uploaded by

tasinsayed2001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

CSharp OOP2 Topics Codes Examples

This document serves as a teaching handout on core C# OOP concepts, including arrays, loops, classes, inheritance, encapsulation, and polymorphism, with accompanying code examples. It covers essential topics such as constructors, access modifiers, and method overloading/overriding, providing practical illustrations for each concept. Additionally, it includes a combined mini project to demonstrate the integration of these concepts in a real-world scenario.

Uploaded by

tasinsayed2001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C# OOP2 Core Topics with Codes and Examples

Prepared as a compact teaching handout for students. Topics include arrays, loops, foreach, enum, class/object,
constructors, inheritance, encapsulation, properties, polymorphism, access modifiers, ref, out, and params.

Topic List
No. Topic Main Use
1 Array Store multiple values of same type
2 Loops Repeat code
3 foreach Read every item from
array/collection
4 Class and Object Create real-world models
5 Constructor Initialize object automatically
6 Parameterized Constructor Initialize object with values
7 Enum Fixed set of options
8 Encapsulation Protect data using private fields
9 Properties Controlled access using get/set
10 Inheritance Reuse parent class members
11 Access Modifiers Control visibility
12 Polymorphism Same method name, different
behavior
13 ref Modify original variable
14 out Return multiple values
15 params Accept many arguments
16 Combined Mini Project Use multiple concepts together

1. Array
Concept: An array stores multiple values of the same data type using one variable name.

using System;

class Program
{
static void Main()
{
int[] marks = { 80, 70, 90, 60, 85 };

[Link]("First mark: " + marks[0]);


[Link]("Second mark: " + marks[1]);

int total = 0;

for (int i = 0; i < [Link]; i++)


{
total += marks[i];
}

double average = (double)total / [Link];

[Link]("Total: " + total);


[Link]("Average: " + average);
}
}

Explanation: Array index starts from 0. [Link] gives the total number of elements.
2. Loops: for, while, do-while
Concept: Loops are used when the same task needs to run again and again.

using System;

class Program
{
static void Main()
{
[Link]("For Loop:");
for (int i = 1; i <= 5; i++)
{
[Link](i);
}

[Link]("While Loop:");
int j = 1;
while (j <= 5)
{
[Link](j);
j++;
}

[Link]("Do While Loop:");


int k = 1;
do
{
[Link](k);
k++;
}
while (k <= 5);
}
}

Explanation: for is good when repeat count is known. while checks condition first. do-while runs at least once.

3. foreach Loop
Concept: foreach is used to read every item from an array or collection easily.

using System;

class Program
{
static void Main()
{
string[] names = { "Rahim", "Karim", "Nabila" };

foreach (string name in names)


{
[Link](name);
}
}
}

Explanation: foreach is simpler than for when we only need to visit each item.

4. Class and Object


Concept: A class is a blueprint. An object is a real item created from that blueprint.
using System;

class Student
{
public string Name;
public int Age;

public void DisplayInfo()


{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
}
}

class Program
{
static void Main()
{
Student s1 = new Student();

[Link] = "Rahim";
[Link] = 21;

[Link]();
}
}

Explanation: Student is the class. s1 is an object. Fields store data and methods perform actions.

5. Default Constructor
Concept: A constructor runs automatically when an object is created.

using System;

class Student
{
public string Name;
public int Age;

public Student()
{
Name = "Unknown";
Age = 0;
}

public void DisplayInfo()


{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
}
}

class Program
{
static void Main()
{
Student s1 = new Student();
[Link]();
}
}

Explanation: This constructor has no parameter, so it is called a default constructor.


6. Parameterized Constructor
Concept: A parameterized constructor receives values and assigns them during object creation.

using System;

class Student
{
public string Name;
public int Age;

public Student(string name, int age)


{
Name = name;
Age = age;
}

public void DisplayInfo()


{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
}
}

class Program
{
static void Main()
{
Student s1 = new Student("Karim", 22);
Student s2 = new Student("Nabila", 20);

[Link]();
[Link]();
[Link]();
}
}

Explanation: This reduces repeated object assignment code.

7. Array of Objects
Concept: An array can store multiple objects of the same class.

using System;

class Student
{
public string Name;
public int Marks;

public Student(string name, int marks)


{
Name = name;
Marks = marks;
}

public void Display()


{
[Link]("Name: " + Name);
[Link]("Marks: " + Marks);
}
}

class Program
{
static void Main()
{
Student[] students = new Student[3];

students[0] = new Student("Rahim", 80);


students[1] = new Student("Karim", 75);
students[2] = new Student("Nabila", 90);

foreach (Student student in students)


{
[Link]();
[Link]();
}
}
}

Explanation: This is useful for student lists, product lists, patient lists, etc.

8. Enum
Concept: Enum is used when a variable should have only fixed values.

using System;

enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}

class Order
{
public int OrderId;
public string CustomerName;
public OrderStatus Status;

public void Display()


{
[Link]("Order ID: " + OrderId);
[Link]("Customer: " + CustomerName);
[Link]("Status: " + Status);

if (Status == [Link])
[Link]("Your order is on the way.");
}
}

class Program
{
static void Main()
{
Order order1 = new Order();
[Link] = 101;
[Link] = "Tanvir";
[Link] = [Link];

[Link]();
}
}

Explanation: Enum prevents invalid random text values for status.


9. Encapsulation
Concept: Encapsulation protects data by keeping fields private and using public methods.

using System;

class BankAccount
{
private double balance;

public void Deposit(double amount)


{
if (amount > 0)
{
balance += amount;
[Link]("Deposit successful.");
}
else
{
[Link]("Invalid amount.");
}
}

public void Withdraw(double amount)


{
if (amount <= balance)
{
balance -= amount;
[Link]("Withdraw successful.");
}
else
{
[Link]("Insufficient balance.");
}
}

public double GetBalance()


{
return balance;
}
}

class Program
{
static void Main()
{
BankAccount account = new BankAccount();

[Link](5000);
[Link](1200);

[Link]("Current Balance: " + [Link]());


}
}

Explanation: The balance cannot be changed directly from Main, so the data is protected.

10. Properties
Concept: Properties provide controlled access to private fields using get and set.

using System;

class Student
{
private string name;
private double cgpa;

public string Name


{
get { return name; }
set { name = value; }
}

public double Cgpa


{
get { return cgpa; }
set
{
if (value >= 0.0 && value <= 4.0)
cgpa = value;
else
[Link]("Invalid CGPA.");
}
}

public void Display()


{
[Link]("Name: " + Name);
[Link]("CGPA: " + Cgpa);
}
}

class Program
{
static void Main()
{
Student s1 = new Student();

[Link] = "Ayesha";
[Link] = 3.75;

[Link]();
}
}

Explanation: The set block validates CGPA before assigning it.

11. Inheritance
Concept: Inheritance allows a derived class to reuse fields and methods of a base class.

using System;

class Person
{
public string Name;
public int Age;

public void ShowPersonInfo()


{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
}
}

class Student : Person


{
public string StudentId;
public void ShowStudentInfo()
{
ShowPersonInfo();
[Link]("Student ID: " + StudentId);
}
}

class Program
{
static void Main()
{
Student s1 = new Student();

[Link] = "Karim";
[Link] = 22;
[Link] = "23-50000-1";

[Link]();
}
}

Explanation: Student inherits Name, Age, and ShowPersonInfo from Person.

12. Inheritance with base Constructor


Concept: The base keyword is used to call the parent class constructor.

using System;

class Person
{
public string Name;
public int Age;

public Person(string name, int age)


{
Name = name;
Age = age;
}
}

class Student : Person


{
public string StudentId;

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


{
StudentId = studentId;
}

public void Display()


{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
[Link]("Student ID: " + StudentId);
}
}

class Program
{
static void Main()
{
Student s1 = new Student("Jubair", 25, "23-12345-1");
[Link]();
}
}

Explanation: : base(name, age) sends name and age to the Person constructor.

13. Access Modifiers


Concept: Access modifiers control where fields and methods can be accessed from.

using System;

class Employee
{
public string Name;
private double bonus;
protected double salary;

public void SetSalary(double amount)


{
salary = amount;
}

public void SetBonus(double amount)


{
bonus = amount;
}

public double GetBonus()


{
return bonus;
}
}

class Manager : Employee


{
public void ShowSalary()
{
[Link]("Name: " + Name);
[Link]("Salary: " + salary);
[Link]("Bonus: " + GetBonus());
}
}

class Program
{
static void Main()
{
Manager m1 = new Manager();

[Link] = "Rahim";
[Link](50000);
[Link](10000);

[Link]();
}
}

Explanation: public can be used anywhere, private only inside the same class, protected inside parent and child class.

14. Polymorphism: Method Overloading


Concept: Method overloading means same method name but different parameters.
using System;

class Calculator
{
public int Add(int a, int b)
{
return a + b;
}

public int Add(int a, int b, int c)


{
return a + b + c;
}

public double Add(double a, double b)


{
return a + b;
}
}

class Program
{
static void Main()
{
Calculator cal = new Calculator();

[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}

Explanation: C# decides which Add method to call based on number and type of arguments.

15. Polymorphism: Method Overriding


Concept: Method overriding means child class changes the parent class method behavior.

using System;

class Animal
{
public virtual void Sound()
{
[Link]("Animal makes sound");
}
}

class Dog : Animal


{
public override void Sound()
{
[Link]("Dog barks");
}
}

class Cat : Animal


{
public override void Sound()
{
[Link]("Cat meows");
}
}

class Program
{
static void Main()
{
Dog dog = new Dog();
Cat cat = new Cat();

[Link]();
[Link]();
}
}

Explanation: virtual allows overriding. override changes the method in the child class.

16. ref
Concept: ref passes the original variable to a method, so the method can change it.

using System;

class Program
{
static void IncreaseSalary(ref double salary)
{
salary = salary + salary * 0.10;
}

static void Main()


{
double employeeSalary = 30000;

[Link]("Before: " + employeeSalary);

IncreaseSalary(ref employeeSalary);

[Link]("After: " + employeeSalary);


}
}

Explanation: The variable must already have a value before using ref.

17. out
Concept: out is used when a method needs to return multiple values.

using System;

class Program
{
static void CalculateRectangle(double length, double width, out double area, out double perimeter)
{
area = length * width;
perimeter = 2 * (length + width);
}

static void Main()


{
double area;
double perimeter;

CalculateRectangle(10, 5, out area, out perimeter);

[Link]("Area: " + area);


[Link]("Perimeter: " + perimeter);
}
}

Explanation: out variables do not need initial values, but the method must assign them.

18. params
Concept: params allows a method to accept any number of arguments.

using System;

class Program
{
static int CalculateTotal(params int[] marks)
{
int total = 0;

foreach (int mark in marks)


{
total += mark;
}

return total;
}

static void Main()


{
int total1 = CalculateTotal(80, 90, 70);
int total2 = CalculateTotal(75, 85, 95, 60, 70);

[Link]("Student 1 Total: " + total1);


[Link]("Student 2 Total: " + total2);
}
}

Explanation: params must be the last parameter of a method.

19. Combined Mini Project: Gym Member System


Concept: This project combines enum, inheritance, class/object, array, foreach, and condition.

using System;

enum GymStatus
{
Regular,
Premium
}

class Person
{
public string Name;
public int Age;
}

class GymMember : Person


{
public string StudentId;
public string Department;
public int WorkoutDays;
public GymStatus Status;
public string[] Exercises;
public void DisplayInfo()
{
[Link]("Name: " + Name);
[Link]("Age: " + Age);
[Link]("Student ID: " + StudentId);
[Link]("Department: " + Department);
[Link]("Workout Days: " + WorkoutDays);
[Link]("Status: " + Status);

[Link]("Exercises:");
foreach (string exercise in Exercises)
{
[Link]("- " + exercise);
}

if (Status == [Link] && WorkoutDays >= 4)


[Link]("Eligible for Personal Trainer");
else
[Link]("Not Eligible for Personal Trainer");
}
}

class Program
{
static void Main()
{
GymMember m1 = new GymMember();
[Link] = "Rafi";
[Link] = 21;
[Link] = "23-70101-1";
[Link] = "CSE";
[Link] = 5;
[Link] = [Link];
[Link] = new string[] { "Cardio", "Weight Training" };

GymMember m2 = new GymMember();


[Link] = "Mitu";
[Link] = 20;
[Link] = "23-70102-1";
[Link] = "BBA";
[Link] = 3;
[Link] = [Link];
[Link] = new string[] { "Yoga" };

GymMember m3 = new GymMember();


[Link] = "Sami";
[Link] = 22;
[Link] = "23-70103-1";
[Link] = "EEE";
[Link] = 4;
[Link] = [Link];
[Link] = new string[] { "Cardio", "Cycling" };

GymMember[] members = { m1, m2, m3 };

foreach (GymMember member in members)


{
[Link]();
[Link]();
}
}
}

Explanation: The GymMember class inherits from Person. Enum controls status. Array stores multiple members. foreach displays all
members and exercises.
Quick Revision Tables
Access Modifiers
Modifier Meaning
public Accessible from anywhere
private Accessible only inside same class
protected Accessible inside same class and child class
internal Accessible inside same project

ref vs out vs params


Keyword Purpose Important Rule
ref Modify original variable Variable must be initialized before
method call
out Return multiple values Method must assign value before
ending
params Accept many values Must be the last parameter
End of Handout

You might also like