# Unit - II (English Version -  for papers)

## 1. **C# Object-Oriented Programming (OOPs)**

C# follows the principles of Object-Oriented Programming (OOP), focusing on organizing code around objects rather than actions. Here's a more detailed breakdown:

### **1.1. Encapsulation**

Encapsulation is about **hiding the internal state** of an object and only exposing **what is necessary** for other parts of the program to interact with. This is achieved through **access modifiers** and **properties**.

**Why is Encapsulation important?**

* **Data Protection**: It ensures that the internal state of an object is protected from unintended or unauthorized modification.
* **Code Maintenance**: You can modify internal logic or implementation without affecting the external interface, thus making the system more flexible and easier to maintain.

Example of encapsulation:

```csharp
public class BankAccount
{
    private double balance; // private field, not directly accessible

    // Public method to access and modify the private field
    public void Deposit(double amount)
    {
        if (amount > 0)
            balance += amount;
    }

    public double GetBalance() // Public method to get the balance
    {
        return balance;
    }
}
```

Here, the `balance` is encapsulated within the `BankAccount` class, and access to it is controlled through public methods like `Deposit` and `GetBalance`.

***

### **1.2. Inheritance**

Inheritance enables **code reuse** by allowing a class to inherit members (fields and methods) from another class. This helps to **extend or modify** the behavior of an existing class, avoiding redundancy.

**Types of Inheritance in C#**:

* **Single Inheritance**: A class can inherit from only one base class.
* **Multilevel Inheritance**: A class inherits from a derived class, which itself inherits from another class (forming a hierarchy).

**Example**:

```csharp
class Vehicle
{
    public void StartEngine()
    {
        Console.WriteLine("Engine started.");
    }
}

class Car : Vehicle // Inherits from Vehicle
{
    public void Honk()
    {
        Console.WriteLine("Horn honked.");
    }
}
```

The `Car` class inherits from `Vehicle`, and thus has access to `StartEngine()`. This shows how inheritance helps in code reuse and extension.

**Key Concepts**:

* **Overriding Methods**: Derived classes can override base class methods to provide custom functionality. This is achieved using the `virtual` keyword in the base class and the `override` keyword in the derived class.

```csharp
class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}
```

***

### **1.3. Polymorphism**

Polymorphism enables objects of different types to be treated as objects of a common base type. It allows the same method or property to behave differently based on the object type.

**Types of Polymorphism**:

* **Compile-time Polymorphism**: Achieved through **method overloading** and **operator overloading**.
* **Run-time Polymorphism**: Achieved through **method overriding**, typically using base class references to hold derived class objects.

Example of **Compile-time Polymorphism (Method Overloading)**:

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

Here, the `Add` method is overloaded to accept both integers and doubles, providing the same functionality but with different input types.

Example of **Run-time Polymorphism (Method Overriding)**:

```csharp
class Animal
{
    public virtual void Speak()
    {
        Console.WriteLine("Animal speaks");
    }
}

class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine("Dog barks");
    }
}
```

If you have a `Dog` object but reference it as an `Animal` type, calling `Speak()` will invoke the overridden method in `Dog`.

***

### **1.4. Object Lifetime**

In C#, objects are created and destroyed automatically by the **Garbage Collector (GC)**. The GC manages the memory of objects and ensures that objects which are no longer referenced are disposed of to free memory.

**Types of Objects**:

* **Reference Types** (Classes, Arrays, Strings): Stored on the **Heap** and managed by the GC.
* **Value Types** (int, double, struct): Stored on the **Stack**.

The GC runs automatically to reclaim memory, but you can control object lifetime using **finalizers** or implementing the `IDisposable` interface.

```csharp
class Example : IDisposable
{
    public void Dispose()
    {
        // Code to release resources
    }
}
```

**GC Example**:

```csharp
class Test
{
    static void Main()
    {
        Test obj = new Test();
        // After this, obj is eligible for GC if no longer referenced.
    }
}
```

***

### **1.5. Components and Modules**

**Components** are self-contained, reusable units of software functionality. **Modules** refer to groups of related components. These terms help in organizing large software systems into smaller, manageable pieces, improving maintainability and scalability.

**Example**:

* **Component**: A class library for authentication, which can be reused in different applications.
* **Module**: A set of components that handle user authentication, logging, and error management.

**Use in C#**:

* **Assemblies**: Components are often packaged into **assemblies**, which are either **DLLs** or **EXEs**.

**Namespaces** in C# are used to organize these components logically, for example, `System.Collections.Generic` for collection classes.

***

### **1.6. Windows Forms**

Windows Forms is a GUI framework for building desktop applications in C#. It uses a drag-and-drop approach to designing the user interface, making it simple to develop applications with graphical elements like buttons, textboxes, and menus.

**Key Components**:

* **Controls**: UI elements such as buttons, labels, and textboxes.
* **Events**: Actions like button clicks or key presses that trigger functions.
* **Form**: The main window of the application.

Example:

```csharp
public class MyForm : Form
{
    public MyForm()
    {
        Button btn = new Button();
        btn.Text = "Click Me";
        btn.Click += new EventHandler(Button_Click);
        Controls.Add(btn);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Button clicked!");
    }
}
```

***

### **1.7. Interface**

An interface in C# defines a contract of methods (without implementation) that a class must implement. Interfaces promote loose coupling by allowing classes to implement behaviors without committing to a specific base class.

**Key Points**:

* **Multiple Inheritance**: C# supports implementing multiple interfaces, which is useful when a class needs to inherit multiple behaviors.
* **Interface vs Abstract Class**: An interface is purely abstract, while an abstract class can provide both abstract methods and concrete methods with implementation.

```csharp
public interface IDriveable
{
    void Drive();
}

public class Car : IDriveable
{
    public void Drive()
    {
        Console.WriteLine("Car is driving");
    }
}
```

***

### **1.8. Cloneable Objects**

Objects in C# can be made **cloneable** by implementing the `ICloneable` interface, which provides a `Clone()` method. You can create either a **shallow copy** or a **deep copy**.

* **Shallow Clone**: Only the object itself is copied; the referenced objects are not.
* **Deep Clone**: A new instance is created, and all referenced objects are also copied.

Example of **ICloneable**:

```csharp
class Person : ICloneable
{
    public string Name { get; set; }
    public int Age { get; set; }

    public object Clone()
    {
        return new Person { Name = this.Name, Age = this.Age };
    }
}
```

***

### **1.9. Comparable Objects**

An object is **comparable** if it implements the `IComparable<T>` interface. This allows you to define how objects of a class should be compared using the `CompareTo` method. The result should be:

* A negative value if the current object is less than the other.
* A positive value if the current object is greater than the other.
* Zero if they are equal.

```csharp
class Person : IComparable<Person>
{
    public string Name { get; set; }

    public int CompareTo(Person other)
    {
        return string.Compare(this.Name, other.Name);
    }
}
```

***

### **1.10. Collections and Namespaces**

In C#, collections are groups of objects, such as arrays, lists, dictionaries, and queues. They are organized under different namespaces, such as `System.Collections` and `System.Collections.Generic`.

**Common Collections**:

* **List**: A dynamic array that resizes automatically.
* **Dictionary\<TKey, TValue>**: A collection of key-value pairs.
* **Queue**: A first-in, first-out (FIFO) collection.
* **Stack**: A last-in, first-out (LIFO) collection.

```csharp
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4);
```

***

## 2. **Advanced Class Construction**

### **2.1. Custom Indexer**

An **indexer** allows an object to be indexed like an array. It enables an object to be accessed using an index, providing custom behavior for indexing.

```csharp
class MyCollection
{
    private int[] data = new int[5];

    public int this[int index]
    {
        get { return data[index]; }
        set { data[index] = value; }
    }
}
```

### **2.2. Overloading Operators**

C# allows you to **overload operators** to provide custom behavior for built-in operators. This helps make your code more expressive.

```csharp
class Point
{
    public int X, Y;

    public static Point operator +(Point p1, Point p2)
    {
        return new Point { X = p1.X + p2.X, Y = p1.Y + p2.Y };
    }
}
```

### **2.3. Delegates**

A **delegate** is a type that represents references to methods with a particular parameter list and return type. It is often used for **callback methods** and event handling.

```csharp
delegate void PrintMessage(string message);

class Program
{
    static void Print(string message)
    {
        Console.WriteLine(message);
    }

    static void Main()
    {
        PrintMessage print = Print;
        print("Hello, World!");
    }
}
```

### **2.4. Events**

An **event** is a way for a class to notify other classes or objects about an occurrence, following the observer pattern. An event is based on **delegates**.

```csharp
public event EventHandler MyEvent;

void OnMyEvent()
{
    MyEvent?.Invoke(this, EventArgs.Empty);
}
```

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://v3noms-organization.gitbook.io/v3noms-byte/.net-framework-notes/.net-framework-syllabus/unit-ii-english-version-for-papers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
