unit2
unit2
1. OOP Concepts in C#
2. Encapsulation
Example:
class BankAccount
}
}
3. Inheritance
Definition: A class can inherit members from another class using the : symbol.
Base Class: Parent class providing members.
Example:
class Animal
{
public void Speak() => Console.WriteLine("Animal sound");
}
4. Polymorphism
Run-Time Polymorphism: Achieved using method overriding with virtual and override
keywords.
Example:
class Shape
{
{
public override void Draw() => Console.WriteLine("Drawing a circle");
5. Object Lifetime
Key Methods:
class Example
{
public Example() { Console.WriteLine("Constructor called"); }
~Example() { Console.WriteLine("Destructor called"); }
7. Windows Forms
Example:
MessageBox.Show("Button clicked!");
8. Interfaces
Definition: A contract that defines methods/properties a class must implement.
Syntax:
interface IAnimal
{
void Speak();
}
}
9. Cloneable and Comparable Objects
Cloneable:
Implemented using ICloneable interface for deep/shallow copy.
{
public string Name { get; set; }
Comparable:
Used to compare objects, implemented via IComparable.
class Student : IComparable<Student>
{
public int Marks { get; set; }
numbers.Add(4);
Console.WriteLine(numbers[2]);
a. Custom Indexers
Definition: Allows objects to be indexed like arrays.
Example:
class Sample
{
get => data[index];
set => data[index] = value;
b. Operator Overloading
Example:
class Complex
c. Delegates
Syntax:
delegate void MyDelegate(string message);
Example:
class Program
{
MyDelegate del = PrintMessage;
del("Hello, Delegates!");
d. Events
Example:
class Publisher
{
class Subscriber
{
pub.Notify();