0% found this document useful (0 votes)
9 views41 pages

#Net

The document explains Object-Oriented Programming (OOP) concepts in C# including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, providing syntax examples for each. It also covers abstraction and interfaces, detailing their differences and when to use each, along with examples of constructors and their types. Additionally, it discusses ADO.NET architecture, emphasizing its components and the disconnected nature of data access.

Uploaded by

aimlessbrothers1
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)
9 views41 pages

#Net

The document explains Object-Oriented Programming (OOP) concepts in C# including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, providing syntax examples for each. It also covers abstraction and interfaces, detailing their differences and when to use each, along with examples of constructors and their types. Additionally, it discusses ADO.NET architecture, emphasizing its components and the disconnected nature of data access.

Uploaded by

aimlessbrothers1
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

Q1. Explain Object-Oriented Programming concepts in C# with examples.

Definition:

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around
objects rather than functions or logic.
It helps to achieve reusability, modularity, and maintainability of code.

Main Concepts of OOP in C#:

1. Class

A class is a blueprint or template that defines variables (fields) and methods for objects.

Syntax Example:

class Student

public string name;

public int age;

public void display()

[Link]("Name: " + name + ", Age: " + age);

2. Object

An object is an instance of a class.


It represents real-world entities such as a student, car, or employee.

Example:

Student s1 = new Student();

[Link] = "Pranesh";

[Link] = 21;

[Link]();

Output:
Name: Pranesh, Age: 21
3. Inheritance

Inheritance allows one class to acquire properties and methods of another class.
It promotes code reusability.

Example:

class Animal

public void Eat()

[Link]("Eating...");

class Dog : Animal

public void Bark()

[Link]("Barking...");

class Test

static void Main()

Dog d = new Dog();

[Link](); // inherited

[Link](); // own method

Output:

Eating...
Barking...

4. Polymorphism

Polymorphism means “many forms” — it allows methods to have the same name but behave differently.

(a) Compile-Time Polymorphism – Method Overloading

class MathOp

public int Add(int a, int b) => a + b;

public double Add(double a, double b) => a + b;

(b) Run-Time Polymorphism – Method Overriding

class Base

public virtual void Show() => [Link]("Base class");

class Derived : Base

public override void Show() => [Link]("Derived class");

5. Abstraction

Abstraction means showing essential features and hiding implementation details.

Example using Abstract Class:

abstract class Shape

public abstract void Draw();

class Circle : Shape

public override void Draw()


{

[Link]("Drawing Circle");

6. Encapsulation

Encapsulation is the binding of data and methods together into a single unit (class).
It also hides data using getters and setters.

Example:

class Account

private double balance;

public void SetBalance(double b) { balance = b; }

public double GetBalance() { return balance; }

Advantages of OOP:

• Code Reusability (through Inheritance)

• Data Security (through Encapsulation)

• Easy Maintenance

• Real-world modeling

• Flexibility through Polymorphism

Conclusion:

OOP in C# provides a powerful way to structure programs.


By combining classes, objects, inheritance, polymorphism, abstraction, and encapsulation,
developers can create robust, modular, and scalable applications.
Q2. Explain Abstraction and Interface in C# with suitable examples.

(Include difference, when to use which, and short programs.)

Definition of Abstraction

Abstraction is the process of hiding internal details and showing only essential features of an object.
It focuses on what an object does rather than how it does it.
In C#, abstraction is achieved using abstract classes and interfaces.

1. Abstraction Using Abstract Class

An abstract class is a base class that cannot be instantiated directly.


It may contain abstract methods (without body) and non-abstract methods (with implementation).

Syntax Example:

abstract class Shape

public abstract void Draw(); // abstract method

public void Color()

[Link]("Shape is colored");

class Circle : Shape

public override void Draw()

[Link]("Drawing Circle...");

class Test

static void Main()

Shape s = new Circle(); // reference of abstract class

[Link]();

[Link]();
}

Output:

Drawing Circle...

Shape is colored

Explanation:

• Shape defines the structure but hides how the Draw() is implemented.

• Circle provides its own implementation of Draw().

2. Abstraction Using Interface

An interface is a completely abstract type that only contains method declarations and properties (no implementation).
A class that implements an interface must define all its methods.

Example:

interface IVehicle

void Start();

void Stop();

class Car : IVehicle

public void Start()

[Link]("Car started...");

public void Stop()

[Link]("Car stopped...");

class TestInterface

static void Main()

{
IVehicle v = new Car();

[Link]();

[Link]();

Output:

Car started...

Car stopped...

Difference between Abstract Class and Interface

Feature Abstract Class Interface

Can have abstract & concrete (defined)


Definition Only has abstract methods (till C# 7.0)
methods.

Not supported (a class can inherit only one


Multiple Inheritance Supported (a class can implement multiple interfaces).
abstract class).

Can have access modifiers (public, protected,


Access Modifiers All members are public by default.
etc.)

Fields and
Can have fields, properties, and constructors. Cannot have fields or constructors.
Constructors

When you have common code to share When you want to define a contract or behavior for
When to Use
among subclasses. multiple unrelated classes.

When to Use Which

Situation Use

You have a base class with shared logic and some abstract methods. Abstract Class

You want common behavior rules for different classes (like IVehicle, IAnimal). Interface

Example (Combined Concept)

abstract class Employee

public abstract void CalculateSalary();

interface IWork

void DoWork();
{

class Manager : Employee, IWork

public override void CalculateSalary()

[Link]("Manager Salary: 80000");

public void DoWork()

[Link]("Managing team...");

class Demo

static void Main()

Manager m = new Manager();

[Link]();

[Link]();

Output:

Manager Salary: 80000

Managing team...

Advantages of Abstraction & Interface

• Hides implementation complexity.

• Improves flexibility and maintainability.

• Enhances reusability and reduces duplication.

• Supports loose coupling.

Conclusion: Abstraction and Interfaces in C# help design programs that are modular, scalable, and easily maintainable.
Use abstract classes when you have shared functionality, and use interfaces when you want to enforce behavior across multiple
unrelated classes.
Q3. Explain Inheritance in C# with its types and example.

(Single, Multilevel, Hierarchical – include diagram and program.)

Definition:

Inheritance is an OOP concept where one class (child/derived class) acquires properties and methods of another class
(parent/base class).
It promotes code reusability and extensibility.

Syntax:

class DerivedClass : BaseClass

// new members

Advantages:

• Reusability of code

• Reduces duplication

• Easier maintenance

• Supports polymorphism

Types of Inheritance in C#:

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
(C# doesn’t support multiple inheritance with classes, but supports via interfaces)

1. Single Inheritance

Diagram:

Animal → Dog

Example:

class Animal {

public void Eat() { [Link]("Eating..."); }

class Dog : Animal {

public void Bark() { [Link]("Barking..."); }

}
class Test1 {

static void Main() {

Dog d = new Dog();

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

Output:
Eating...
Barking...

2. Multilevel Inheritance

Diagram:

Animal → Dog → Puppy

Example:

class Animal { public void Eat() { [Link]("Eating"); } }

class Dog : Animal { public void Bark() { [Link]("Barking"); } }

class Puppy : Dog { public void Weep() { [Link]("Weeping"); } }

class Test2 {

static void Main() {

Puppy p = new Puppy();

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

Output:
Eating
Barking
Weeping

3. Hierarchical Inheritance

Diagram:

Animal

├── Dog

└── Cat

Example:

class Animal { public void Eat() { [Link]("Eating"); } }

class Dog : Animal { public void Bark() { [Link]("Barking"); } }

class Cat : Animal { public void Meow() { [Link]("Meowing"); } }


class Test3 {

static void Main() {

Dog d = new Dog(); [Link](); [Link]();

Cat c = new Cat(); [Link](); [Link]();

Output:
Eating
Barking
Eating
Meowing

Types Summary Table

Type Description Example

Single One base → one derived Animal → Dog

Multilevel Chain of inheritance Animal → Dog → Puppy

Hierarchical One base → many derived Animal → Dog, Cat

Key Points:

• Keyword used: :

• Base class constructor runs before derived class

• Private members are not inherited

• Supports reusability and extensibility

Conclusion:

Inheritance allows new classes to reuse and extend existing functionality, improving efficiency and modular design in C# programs.
Q4. Explain Method Overloading and Method Overriding with examples.

(Compile-time vs Run-time Polymorphism, base & override examples.)

Definition of Polymorphism:

Polymorphism means “many forms”.


It allows methods to perform different tasks using the same name.
In C#, polymorphism is of two types:
Compile-time Polymorphism (Method Overloading)
Run-time Polymorphism (Method Overriding)

1. Method Overloading (Compile-time Polymorphism)

• Same method name, different parameter lists (number or type).

• Decided by the compiler at compile time.

• Achieved within the same class.

Example:

class MathOp {

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

public double Add(double a, double b) { return a + b; }

class Test {

static void Main() {

MathOp m = new MathOp();

[Link]([Link](5, 3));

[Link]([Link](2.5, 3.7));

Output:
8
6.2

Here, the Add() method behaves differently based on arguments.

2. Method Overriding (Run-time Polymorphism)

• Same method name & signature, but different implementation in derived class.

• Determined at run time using the virtual and override keywords.

• Achieved via inheritance.


Example:

class Animal {

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

class Dog : Animal {

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

class Test2 {

static void Main() {

Animal a = new Dog(); // base reference, derived object

[Link]();

Output:
Dog barks

The method from the derived class overrides the base class version.

Difference between Overloading & Overriding

Feature Method Overloading Method Overriding

Type Compile-time Run-time

Class Same class Different classes (inheritance)

Keywords None virtual & override

Signature Must differ Must be same

Binding Early binding Late binding

Example Add(int,int), Add(double,double) Base → Derived Sound()

Base Keyword Example:

class Parent {

public virtual void Show() { [Link]("Parent method"); }

class Child : Parent {

public override void Show() {

[Link](); // call base method

[Link]("Child method");

}
}

class Demo {

static void Main() {

Child c = new Child();

[Link]();

Output:
Parent method
Child method

Advantages of Polymorphism:

• Increases code flexibility and reusability.

• Allows dynamic method behavior.

• Simplifies code maintenance.

Conclusion:

Polymorphism in C# allows one interface to be used for different data types or classes.
Overloading handles it at compile-time, while Overriding achieves it at run-time using inheritance.

Q5. Explain Constructors in C# and their types.

(Default, Parameterized, Copy, Static Constructor – with examples.)

Definition:

A Constructor is a special method in C# that is automatically called when an object is created.


It is used to initialize data members of a class.
Constructor name is same as the class name and has no return type.

Syntax:

class ClassName

public ClassName() // Constructor

// initialization code

}
Rules of Constructors:

• Name must be same as the class.

• No return type (not even void).

• Automatically invoked on object creation.

• Can be overloaded but not inherited.

Types of Constructors in C#:

Default Constructor
Parameterized Constructor
Copy Constructor
Static Constructor

1. Default Constructor

A constructor with no parameters. It initializes data with default values.

class Student {

public Student() {

[Link]("Default Constructor called");

class Test {

static void Main() {

Student s1 = new Student();

Output:
Default Constructor called

2. Parameterized Constructor

Used to initialize object with custom values.

class Student {

string name; int age;

public Student(string n, int a) {

name = n; age = a;

public void Show() {

[Link]("Name: " + name + ", Age: " + age);

}
}

class Test2 {

static void Main() {

Student s1 = new Student("Pranesh", 21);

[Link]();

Output:
Name: Pranesh, Age: 21

3. Copy Constructor

Used to create a new object by copying data from another object.

class Student {

string name; int age;

public Student(string n, int a) { name = n; age = a; }

public Student(Student s) { name = [Link]; age = [Link]; } // Copy constructor

public void Display() { [Link](name + " " + age); }

class Test3 {

static void Main() {

Student s1 = new Student("Sarees", 18);

Student s2 = new Student(s1);

[Link]();

Output:
Sarees 18

4. Static Constructor

Used to initialize static data members of a class.


It executes only once when the class is loaded, before any object is created.

class Example {

static Example() {

[Link]("Static Constructor called");

public Example() {

[Link]("Normal Constructor called");


}

class Test4 {

static void Main() {

Example e1 = new Example();

Example e2 = new Example();

Output:
Static Constructor called
Normal Constructor called
Normal Constructor called

Summary Table:

Type Parameters Called When Purpose

Default No Object creation Initialize default values

Parameterized Yes Object creation Initialize with user data

Copy Another object Object creation Copy data from existing object

Static None Class load Initialize static data

Advantages:

• Automatically initializes data

• Reduces errors

• Improves code readability

• Supports overloading

Conclusion:

Constructors in C# are special methods that simplify object initialization.


Different types allow flexibility in assigning default, custom, or static values efficiently.

6. [Link] Architecture in C#

Introduction

[Link] (ActiveX Data Objects .NET) is a data access technology used in C# to connect, retrieve, manipulate, and update data
from different data sources like SQL Server, Oracle, or XML.
It provides a bridge between the front-end application and the back-end database.
Architecture of [Link]

The [Link] architecture is disconnected, meaning data can be accessed and modified even without a continuous database
connection.

Main Components

Component Description

Establishes a link between the application and the data source.


Connection
Example: SqlConnection

Executes SQL queries and stored procedures.


Command
Example: SqlCommand

DataReader Provides fast, forward-only, read-only access to data. Used when data is read-only.

DataAdapter Acts as a bridge between the DataSet and the database. It fills data from the database and updates back.

A disconnected, in-memory representation of data (like a mini database). It can hold multiple tables and
DataSet
relationships.

Diagram of [Link] Architecture

Application

---------------------------------

| [Link] Layer |

| |

| Connection <--> Command |

| | | |

| DataAdapter <--> DataSet |

| \ / |

| DataReader |

---------------------------------

Database (SQL Server, Oracle, etc.)

Example Program

using System;

using [Link];

using [Link];
class AdoNetExample

static void Main()

string connectionString = "Data Source=.;Initial Catalog=StudentDB;Integrated Security=True";

SqlConnection con = new SqlConnection(connectionString);

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", con);

DataSet ds = new DataSet();

[Link](ds, "Students");

foreach (DataRow row in [Link]["Students"].Rows)

[Link](row["StudentName"]);

[Link]();

Explanation of the Code

• SqlConnection: Connects to StudentDB.

• SqlDataAdapter: Executes the SQL query and fills data into DataSet.

• DataSet: Holds table data temporarily.

• foreach loop: Reads and prints data.

• Connection is automatically managed by DataAdapter.

Advantages of [Link]

• Disconnected data access improves performance.

• Works with multiple databases.

• XML support for data exchange.

• Secure and reliable connection handling.


Conclusion [Link] provides a robust, secure, and efficient framework for database operations in C#.
Its disconnected architecture makes it ideal for modern web and desktop applications.

7. Exception Handling in C#

Definition

Exception Handling in C# is a mechanism to handle runtime errors gracefully without crashing the program.
It allows developers to detect errors, handle them, and continue program execution safely.

Keywords Used

Keyword Description

try Block of code that may cause an exception.

catch Handles the exception raised in try block.

finally Executes always, whether an exception occurs or not.

throw Used to manually raise an exception.

Basic Example

using System;

class ExceptionExample

static void Main()

try

int num1 = 10, num2 = 0;

int result = num1 / num2; // Exception occurs

[Link](result);

catch (DivideByZeroException ex)

[Link]("Error: Division by zero not allowed!");

finally

[Link]("Execution completed.");

}
}

Output

Error: Division by zero not allowed!

Execution completed.

Explanation:

• try contains code that might fail.

• catch handles the specific exception.

• finally executes always — used for cleanup operations (like closing files or connections).

Custom Exception in C#

You can create your own exceptions by extending the Exception class.

Example:

using System;

class InvalidAgeException : Exception

public InvalidAgeException(string msg) : base(msg) { }

class CustomExceptionDemo

static void Main()

int age = 15;

try

if (age < 18)

throw new InvalidAgeException("Age must be 18 or above to vote!");

else

[Link]("Eligible to vote.");

catch (InvalidAgeException ex)

[Link]("Custom Exception: " + [Link]);

}
}

Output

Custom Exception: Age must be 18 or above to vote!

Advantages

• Prevents program crashes.

• Improves readability and debugging.

• Allows handling of specific error types.

• Ensures cleanup using finally.

Conclusion

Exception handling in C# ensures smooth program flow and reliability by handling unexpected runtime errors effectively.
Using try-catch-finally and custom exceptions, developers can create robust and maintainable applications.

8. Explain Multithreading in C# with Example

(Thread class, Start(), Sleep(), Thread Priorities)

Definition

Multithreading is the process of executing multiple threads simultaneously within a single program to perform multiple tasks
concurrently.
Each thread represents a separate path of execution.

Key Concepts

Term Description

Thread A lightweight process that executes independently.

Main Thread The default thread created by CLR when the program starts.

Thread Class Found in [Link] namespace; used to create and control threads.

Start() Begins thread execution.

Sleep(ms) Suspends thread execution for given milliseconds.

Priority Determines execution importance (Highest, AboveNormal, Normal, BelowNormal, Lowest).

Example Program
using System;

using [Link];

class MultiThreadDemo

// Method executed by threads

public void Display()

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

[Link]([Link] + " : " + i);

[Link](500); // Pause for 0.5 seconds

static void Main()

MultiThreadDemo obj = new MultiThreadDemo();

// Creating threads

Thread t1 = new Thread([Link]);

Thread t2 = new Thread([Link]);

// Naming threads

[Link] = "Thread A";

[Link] = "Thread B";

// Setting priorities

[Link] = [Link];

[Link] = [Link];

// Starting threads

[Link]();

[Link]();

[Link]("Main Thread Finished!");


}

Output (Sample)

Main Thread Finished!

Thread A : 1

Thread B : 1

Thread A : 2

Thread B : 2

Thread A : 3

Thread B : 3

(Order may vary because threads run concurrently.)

Explanation

• Two threads t1 and t2 execute the same method Display() simultaneously.

• Sleep() delays each iteration, showing concurrent execution.

• Thread priorities affect the execution order but not strictly — OS decides scheduling.

Advantages of Multithreading

1. Efficient CPU utilization.

2. Faster program execution.

3. Background tasks (like file download) run smoothly.

4. Better user responsiveness in GUI applications.

Disadvantages

• Complex debugging and synchronization.

• May cause data inconsistency without proper locking.

Conclusion

Multithreading in C# enhances performance by allowing multiple operations to run simultaneously.


Using the Thread class, Start(), Sleep(), and priorities, developers can build responsive and high-speed applications.
9. Explain File Handling in C# with Examples

(FileStream, StreamReader, StreamWriter)

Definition

File Handling in C# allows reading from and writing to files stored on disk.
The classes under [Link] namespace are used to perform file operations such as
create, read, write, and delete.

Important Classes in File Handling

Class Description

FileStream Used for reading/writing bytes to a file.

StreamReader Reads data (text) from a file.

StreamWriter Writes data (text) to a file.

FileStream Example

using System;

using [Link];

class FileStreamDemo

static void Main()

FileStream fs = new FileStream("[Link]", [Link]);

byte[] data = [Link]("Hello C# FileStream!");

[Link](data, 0, [Link]);

[Link]();

[Link]("Data written successfully using FileStream.");

}
}

Explanation:

• [Link] → Creates a new file.

• Write() → Writes bytes to file.

• Close() → Closes the file stream.

StreamWriter Example

using System;

using [Link];

class StreamWriterDemo

static void Main()

StreamWriter sw = new StreamWriter("[Link]");

[Link]("C# File Handling Example");

[Link]("Using StreamWriter Class");

[Link]();

[Link]("Data written to file successfully!");

Explanation:

• StreamWriter is used to write text data easily.

• It automatically encodes text into bytes.

StreamReader Example

using System;

using [Link];
class StreamReaderDemo

static void Main()

StreamReader sr = new StreamReader("[Link]");

string content = [Link]();

[Link]();

[Link]("File Content:\n" + content);

Explanation:

• StreamReader reads all data from the text file.

• ReadToEnd() reads complete file content.

Output

C# File Handling Example

Using StreamWriter Class

Common File Modes in C#:

Mode Description

Create Creates new file or overwrites existing one.

Append Opens file and adds text at end.

Open Opens existing file.

Advantages

• Stores data permanently.


• Easy to manipulate and retrieve information.

• Useful in logging and database backup systems.

Precautions

• Always use Close() or Dispose() to release file resources.

• Use try-catch for handling file I/O exceptions.

Conclusion

File handling in C# enables efficient input/output operations using FileStream,


StreamWriter, and StreamReader.
It helps in building programs that interact with external files — essential for data-driven
and real-world applications.

0. Explain .NET Framework Architecture with Diagram

(CLR, CTS, CLS, FCL, Language Interoperability)

Definition

The .NET Framework is a software development platform developed by Microsoft for building and running applications on
Windows.
It provides a runtime environment, class libraries, and tools to support multiple programming languages (like C#, [Link], F#).

Main Components of .NET Framework Architecture

CLR (Common Language Runtime)

• It is the execution engine of .NET.

• Manages code execution, memory, and resources.

• Converts MSIL (Microsoft Intermediate Language) code into machine code using JIT (Just-In-Time) compiler.

• Provides services like:

o Exception Handling

o Garbage Collection

o Thread Management

o Security and Type Safety


CTS (Common Type System)

• Defines how data types are declared and used in the .NET Framework.

• Ensures that types declared in one language can be used in another (e.g., int in C# = Integer in [Link]).

• Promotes language interoperability.

CLS (Common Language Specification)

• A set of rules and guidelines for all .NET languages.

• Ensures code written in one language can be reused in another.

• Example: If C# uses features that are not CLS-compliant, [Link] may not understand them.

FCL (Framework Class Library)

• A huge collection of predefined classes, interfaces, and namespaces that support:

o File Handling ([Link])

o Database Connectivity ([Link])

o Collections ([Link])

o Networking, XML, and more.

• Reusable and object-oriented.

Language Interoperability

• One of the main strengths of .NET.

• Multiple languages (C#, [Link], F#) can work together because all are compiled to Common Intermediate Language
(CIL), which runs on CLR.

• Enables cross-language integration and code reuse.

Diagram: .NET Framework Architecture

+-----------------------------------------+

| .NET Framework Applications |

| (C#, [Link], F#, [Link], etc.) |

+--------------------+--------------------+

+-----------------------------------------+

| Common Language Runtime (CLR) |

| - Memory Management |

| - Exception Handling |

| - Security & Threading |


| - JIT Compiler |

+-----------------------------------------+

+-----------------------------------------+

| Base Class Library (FCL) |

| - System, IO, Data, Collections, etc. |

+-----------------------------------------+

+-----------------------------------------+

| CTS & CLS |

| - Common Type System |

| - Language Rules & Interoperability |

+-----------------------------------------+

Working Process

1. Source Code (.cs, .vb, etc.) → Compiled into MSIL by the compiler.

2. CLR uses JIT Compiler to convert MSIL into native machine code.

3. Code executes with services like memory management, exception handling, etc.

Advantages

• Language Interoperability

• Strong Security

• Automatic Memory Management

• Large Class Library

• Platform Independence (with .NET Core/5+)

Conclusion

The .NET Framework Architecture provides a robust, secure, and language-independent environment for application
development.
With CLR, CTS, CLS, and FCL, it simplifies the development and execution of high-performance applications.
11. Explain Delegates in C# with Suitable Example

(Include Single-cast and Multi-cast Delegate)

Definition

A Delegate in C# is a type-safe function pointer that holds the reference to a method.


It allows methods to be passed as parameters, invoked dynamically, and is the base for events in C#.

Key Features

• Delegates are objects that can call methods indirectly.

• They ensure type safety — method signature must match the delegate.

• Used for callbacks, event handling, and asynchronous programming.

Syntax

delegate <return_type> <delegate_name>(<parameters>);

Example:

delegate void MyDelegate(string msg);

Single-Cast Delegate Example

using System;

delegate void GreetDelegate(string name);

class SingleCastDemo

static void SayHello(string name)

[Link]("Hello " + name);

static void Main()

// Single-cast delegate pointing to one method

GreetDelegate gd = SayHello;

gd("Pranesh");

}
Output:

Hello Pranesh

Explanation:

• The delegate GreetDelegate points to only one method SayHello.

• When invoked, it executes that method.

Multi-Cast Delegate Example

using System;

delegate void CalcDelegate(int a, int b);

class MultiCastDemo

static void Add(int x, int y)

[Link]("Addition: " + (x + y));

static void Sub(int x, int y)

[Link]("Subtraction: " + (x - y));

static void Main()

// Multicast delegate pointing to multiple methods

CalcDelegate obj = Add;

obj += Sub; // combine methods

obj(20, 10); // invoke all methods

Output:

Addition: 30

Subtraction: 10

Explanation:

• The same delegate instance calls multiple methods sequentially.


• Using += adds another method; -= removes one.

Difference Between Single-Cast and Multi-Cast

Feature Single-Cast Delegate Multi-Cast Delegate

Methods Refers to one method Refers to multiple methods

Operator Uses = Uses += and -=

Use Case Simple method call Sequential execution

Advantages

• Supports loose coupling between methods.

• Enables callback mechanisms.

• Foundation for Events in C#.

Conclusion

Delegates in C# provide a powerful and flexible way to call methods indirectly.


They support both single-cast (one method) and multi-cast (multiple methods) execution, making them essential for event-driven
programming and asynchronous design in .NET.

12. Explain Generics in C# with Suitable Example

(Generic Class, Generic Method, Advantages of Generics)

Definition

Generics in C# allow you to create classes, methods, interfaces, and collections with type parameters.
They provide type safety and code reusability by allowing you to write code that works with any data type without rewriting it.

Key Points

• Introduced in C# 2.0.

• Denoted using angle brackets <T>, where T is a type parameter.

• Eliminates the need for type casting and improves performance.

Generic Class Example

using System;
class GenericClass<T>

private T data;

public GenericClass(T value)

data = value;

public void Display()

[Link]("Value: " + data);

class Program

static void Main()

GenericClass<int> obj1 = new GenericClass<int>(100);

GenericClass<string> obj2 = new GenericClass<string>("C# Generics");

[Link]();

[Link]();

Output:

Value: 100

Value: C# Generics

Explanation:

• <T> makes the class reusable for different data types (int, string, etc.).

• No need to create separate classes for each type.

Generic Method Example

using System;
class GenericMethodDemo

public void ShowData<T>(T value)

[Link]("Data: " + value);

static void Main()

GenericMethodDemo obj = new GenericMethodDemo();

[Link]<int>(25);

[Link]<string>("Hello Generics");

Output:

Data: 25

Data: Hello Generics

Explanation:

• <T> in method defines a generic parameter.

• The same method works with any data type.

Advantages of Generics

Feature Description

Type Safety Errors detected at compile time, no need for casting.

Reusability Same class/method works for any data type.

Performance Avoids boxing/unboxing; faster execution.

Code Clarity Cleaner, maintainable, and less redundant code.

Example Use Case

Generics are heavily used in Collections like:

• List<T>

• Dictionary<TKey, TValue>

• Queue<T>, Stack<T>

Example:
List<string> names = new List<string>();

[Link]("Pranesh");

[Link]("Sardis");

Conclusion

Generics in C# provide a powerful way to create reusable, type-safe, and high-performance code.
They improve efficiency and maintainability by eliminating duplicate definitions for different data types.

13. Explain Namespaces and Assemblies in .NET

(Definition, Types, Usage, Example)

Definition

In .NET, Namespaces and Assemblies are key components used to organize, manage, and deploy code efficiently.

Namespaces

Definition

A Namespace is a logical container used to group related classes, interfaces, enums, and structs together to avoid name
conflicts.
It helps in organizing large codebases in a structured way.

Syntax

namespace MyNamespace

class Demo

public void Show()

[Link]("Hello from MyNamespace!");

Using Namespace

using System;

using MyNamespace;

class Program
{

static void Main()

Demo obj = new Demo();

[Link]();

Output:

Hello from MyNamespace!

Types of Namespaces

Type Description

Built-in Namespace Provided by .NET (e.g., System, [Link], [Link]).

User-defined Namespace Created by developers for custom organization.

Nested Namespace Namespace within another namespace.

Advantages

• Avoids name collisions.

• Increases code readability and maintainability.

• Helps in organizing large projects.

Assemblies

Definition

An Assembly is a physical deployment unit of a .NET application.


It contains compiled code (IL), metadata, and resources, packaged as .exe or .dll files.

Types of Assemblies

Type Description

Private Assembly Used by a single application (stored in app folder).

Shared Assembly Used by multiple applications (stored in Global Assembly Cache - GAC).

Satellite Assembly Contains resources for localization (language-specific).

Structure of an Assembly

An assembly contains:
1. Manifest → metadata about version, culture, dependencies.

2. MSIL Code → compiled Intermediate Language code.

3. Metadata → type and method information.

4. Resources → images, strings, etc.

Example

// Compile the file using: csc /target:library [Link]

namespace MathLib

public class Calculator

public int Add(int a, int b)

return a + b;

This creates a DLL (Dynamic Link Library) — a reusable assembly.

Using the Assembly

using MathLib;

class Program

static void Main()

Calculator c = new Calculator();

[Link]("Sum: " + [Link](5, 10));

Output:

Sum: 15

Difference Between Namespace and Assembly

Feature Namespace Assembly

Meaning Logical grouping of code Physical unit (file) containing code


Feature Namespace Assembly

File Type Exists only in code Compiled as .dll or .exe

Usage Organizes classes logically Used for deployment and execution

Scope Logical (within code) Physical (in file system)

Conclusion

• Namespace organizes and categorizes classes logically.

• Assembly packages compiled code physically for deployment.


Together, they make .NET applications modular, reusable, and manageable.

Q14. Explain Boxing and Unboxing in C# with example.

Definition:
Boxing and Unboxing are processes of converting between value types and reference types in C#.

Boxing:

It is the process of converting a value type (like int, float, etc.) into an object type (reference type).
When a value type is boxed, it is wrapped inside an object and stored on the heap.

Syntax:

object obj = valueType;

Example:

int num = 100; // Value type

object obj = num; // Boxing

[Link](obj);

➡ Here, the integer num is boxed into an object obj.

Unboxing:

It is the process of extracting the value type from the object type.

Syntax:

valueType = (DataType)objectName;

Example:

object obj = 200;

int num = (int)obj; // Unboxing

[Link](num);

➡ The object obj is unboxed to integer num.

Difference between Boxing and Unboxing:


Boxing Unboxing

Converts value type → object Converts object → value type

Stored on heap Extracted from heap

Implicit Explicit (typecasting required)

Slower due to heap allocation May throw exceptions if type mismatched

Diagram:

Stack (value type) → [Boxing] → Heap (object)

Heap (object) → [Unboxing] → Stack (value type)

Use: When you need to store value types in collections like ArrayList (non-generic).

Q15. Explain Value Types and Reference Types with examples.

Value Types:

• Store data directly in memory.

• Stored in the stack.

• Each variable has its own copy of data.

• Derived from [Link].

Examples:
int, float, char, bool, struct, enum.

Example Program:

int x = 10;

int y = x; // copy value

y = 20;

[Link](x); // 10

[Link](y); // 20

➡ Changing y doesn’t affect x since both store separate copies.

Reference Types:

• Store memory address (reference) of the data.

• Stored in the heap.

• Multiple variables can refer to the same object.

• Derived from [Link].

Examples:
class, array, string, interface, delegate.

Example Program:

class Demo
{

public int val;

Demo d1 = new Demo();

[Link] = 30;

Demo d2 = d1; // reference copy

[Link] = 50;

[Link]([Link]); // 50 (changes reflect)

➡ Both d1 and d2 refer to the same memory location.

Difference Table:

Value Type Reference Type

Stores data directly Stores reference to data

Stored in stack Stored in heap

Faster access Slower access

No memory overhead Has memory overhead

Examples: int, float Examples: class, array

Summary:
Value types hold actual data; reference types hold address of the data.
Understanding the difference helps in efficient memory management and data handling in C#.

You might also like