SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
QUESTION BANK SOLUTION
Q 1. Answer any four parts of the following.
a) Illustrate the architecture of .Net Framework with neat diagram.
b) Differentiate between CTS and CLS.
c) How can you handle error in C#? Explain the different technique to handled
error in C#.
d) Why C# is called type safe language? Explain.
e) Write a C# program to print Fibonacci series.
f) Discuss the different types of data types used in C# with example.
SOL:1(a) The .Net Framework architecture consists of the following layers:
1. Common Language Runtime (CLR):
o Manages code execution.
o Handles garbage collection, memory management, security, and thread
management.
2. Base Class Library (BCL):
o Provides reusable classes for system-level functionality, file I/O, strings,
and data collections.
3. Languages:
o Supports multiple programming languages (e.g., C#, [Link]).
4. Application Domain:
o Isolates applications to provide security and stability.
Below is a simplified diagram:
-------------------------------
| Application Code |
-------------------------------
| Base Class Library (BCL) |
-------------------------------
| Common Language Runtime (CLR)|
-------------------------------
| Operating System |
SOL(b): Differentiate between CTS and CLS:
CLS (Common Language
Aspect CTS (Common Type System)
Specification)
Standardizes all data types A subset of CTS ensuring cross-
Definition
across .NET languages. language compatibility.
Deals with data type rules and Specifies rules for language
Focus
structure. interoperability.
Broader, covers all types supported Narrower, supports only CLS-compliant
Scope
in .NET. types.
Helps in achieving consistency in Ensures code from different languages
Purpose
data types. can interoperate.
unsigned int in CTS but not CLS-
Example int, float, and string are CLS-compliant.
compliant.
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Sol(c): Error handling techniques in C#:
1. Using try-catch Block:
o Used to catch and handle exceptions at runtime.
try {
int x = [Link]("abc");
} catch (FormatException ex) {
[Link]("Error: " + [Link]);
}
2 Using finally Block:
Used for cleanup actions, whether an exception occurs or not.
try {
// Code that might throw exceptions.
} finally {
[Link]("Execution complete.");
}
3 Throwing Exceptions:
Custom exceptions can be thrown using throw.
throw new InvalidOperationException("Invalid operation occurred.");
[Link] Error Handling:
o Using a global handler like :
[Link] for unhandled errors.
Sol(d): C# is called a type-safe language because:
Strict Type Checking: The compiler enforces type compatibility at compile-time,
reducing runtime errors.
Managed Memory Access: C# code runs in a CLR-managed environment,
preventing illegal memory access.
Boxing and Unboxing Rules: These ensure controlled conversion between value
types and reference types.
No Arbitrary Pointers: Unless explicitly used in an unsafe context, pointers are
disallowed.
Example:
int number = 10;
string text = "Hello";
// Compile-time error: Cannot implicitly convert 'string' to 'int'.
// number = text;
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Sol(e): Write a C# program to print the Fibonacci series:
using System;
class Program {
static void Main() {
int n1 = 0, n2 = 1, n3, count = 10;
[Link](n1 + " " + n2 + " "); // Printing first two numbers
for (int i = 2; i < count; ++i) {
n3 = n1 + n2;
[Link](n3 + " ");
n1 = n2;
n2 = n3;
}
}
}
Output:
0 1 1 2 3 5 8 13 21 34
Sol(f) :Discuss different types of data types used in C# with examples:
1. Value Types:
o Directly contain data.
o Examples: int, float, char, bool.
int age = 25;
float price = 99.5f;
2. Reference Types:
Store references to memory locations.
Examples: string, object, dynamic.
string name = "John";
object obj = 42; // Can hold any data type
3. Nullable Types:
Allow null value for value types.
int? nullableInt = null;
if ([Link]) [Link]([Link]);
4. Pointer Types (Unsafe Code):Used in unmanaged code scenarios.
unsafe {
int num = 10;
int* ptr = #
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
5. Dynamic Types:Type is resolved at runtime.
dynamic variable = 10;
variable = "Text"; // Allowed
Q 2. Answer any four parts of the following.
a) Write a C# program to illustrate the concept of passing parameters for thread.
b) Illustrate assemblies. Explain the creation and sharing of assemblies in details.
c) Differentiate between boxing and unboxing.
d) What do you understand by run time and compile time polymorphism? Explain
with example.
e) Describe in details about the Windows forms Applications and windows
services?
f) Describe in details about the Features and Architecture of [Link]?
Sol(a): a) Write a C# program to illustrate the concept of passing parameters for
threads:
Using threads with parameters:
using System;
using [Link];
class Program {
// Method that accepts a parameter
static void PrintNumbers(object limit) {
int num = (int)limit;
for (int i = 1; i <= num; i++) {
[Link]($"Number: {i}");
}
}
static void Main() {
// Passing parameter to thread
Thread thread = new Thread(PrintNumbers);
[Link](10); // Pass 10 as parameter
}
}
Explanation:
The method PrintNumbers accepts an object parameter to support passing data.
When creating a thread, PrintNumbers is passed as a delegate.
Parameters are passed using the Start method of the thread.
Sol(b): Illustrate assemblies and explain the creation and sharing of assemblies in
detail:
Assemblies in .NET:
Assemblies are the building blocks of .NET applications.
They contain compiled code, resources, and metadata.
Can be of two types:
1. Private Assemblies: Used by a single application.
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
2. Shared Assemblies: Stored in the Global Assembly Cache (GAC) for
multiple applications.
Components of an Assembly:
1. Manifest: Metadata containing version, culture, and public key.
2. Intermediate Language (IL): Compiled code.
3. Resources: Images, strings, etc.
Creating an Assembly:
1. Write the code (e.g., [Link]):
public class MyLibrary {
public void Greet() {
[Link]("Hello from MyLibrary!");
}
}
2. Compile using the command:
bash
csc /target:library /out:[Link] [Link]
Sol(c): Differentiate between Boxing and Unboxing:
Aspect Boxing Unboxing
Converts an object type back to a
Definition Converts a value type to an object type.
value type.
Enables treating value types as Retrieves value type from reference
Purpose
reference types. type.
Creates additional memory for the
Overhead Accesses the value, slightly faster.
boxed object.
Example int num = 10; object obj = num; int num2 = (int)obj;
Example in C#:
int num = 123; // Value type
object obj = num; // Boxing
int num2 = (int)obj; // Unboxing
[Link](num2);
Sol(d): Compile-Time vs Run-Time Polymorphism:
Polymorphism:
Allows one interface to be used for multiple functions.
1. Compile-Time Polymorphism:
Achieved using method overloading or operator overloading.
Resolved at compile time.
Example: Method Overloading
class MathOperations {
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
}
var math = new MathOperations();
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
[Link]([Link](5, 3)); // Calls int version
[Link]([Link](5.5, 3.2)); // Calls double version
2. Run-Time Polymorphism:
Achieved using method overriding.
Resolved at runtime via virtual functions.
Example: Method Overriding
class Animal {
public virtual void Speak() {
[Link]("Animal speaks");
}
}
class Dog : Animal {
public override void Speak() {
[Link]("Dog barks");
}
}
Animal animal = new Dog();
[Link](); // Outputs: Dog barks
Sol(e): Windows Forms Applications vs Windows Services:
Windows Forms Applications:
Purpose: Build desktop GUI applications.
Features:
o Event-driven model.
o Controls like buttons, text boxes, and labels.
o Easy to use with drag-and-drop GUI designers.
Example:
using [Link];
public class MyForm : Form {
public MyForm() {
Button button = new Button { Text = "Click Me" };
[Link] += (s, e) => [Link]("Hello!");
[Link](button);
}
public static void Main() {
[Link](new MyForm());
}
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Windows Services:
Purpose: Run long-running background processes.
Features:
o Runs in the background, even when no user is logged in.
o Managed using the Service Control Manager (SCM).
Example
using [Link];
public class MyService : ServiceBase {
protected override void OnStart(string[] args) {
// Code to execute when the service starts
}
protected override void OnStop() {
// Code to execute when the service stops
}
}
Sol(f):Features and Architecture of [Link]:
Features of [Link]:
1. Disconnected Architecture: Fetch data and work offline.
2. Data Providers: For databases like SQL Server, Oracle, etc.
3. Scalable: Supports multiple users and large datasets.
4. XML Support: Exchange and store data as XML.
5. Integration: Integrates well with .NET applications.
Architecture of [Link]:
1. Data Providers: Components for database communication.
o Connection: Establishes a connection to the database.
o Command: Executes SQL queries.
o DataReader: Reads data in a forward-only stream.
o DataAdapter: Fills data into DataSet.
2. Disconnected Components:
o DataSet: In-memory cache of data.
o DataTable: Represents a single table in a DataSet.
Example of [Link] to Fetch Data:
using System;
using [Link];
using [Link];
class Program {
static void Main() {
string connectionString = "YourConnectionString";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
[Link]();
SqlDataReader reader = [Link]();
while ([Link]()) {
[Link](reader["Username"]);
}
}
}
}
Explanation:
SqlConnection connects to the database.
SqlCommand executes SQL queries.
SqlDataReader retrieves the results.
Q 3. Answer any two parts of the following.
a) Write short notes on Inheritance? Discuss the various types of Inheritance with
an example? Explain in details about the Interfaces with an example?
b) Describe the Delegates and Events with example.
c) Explain the Array & Types of Array and lists with an example?
Sol(a): Inheritance, Its Types, and Interfaces in C#:
1. Inheritance: Inheritance is a fundamental concept in object-oriented programming
that allows a class to derive properties, methods, and behaviors from another class.
Base Class: The parent class providing common functionality.
Derived Class: The child class inheriting from the base class.
Advantages of Inheritance:
Code reuse.
Easier maintenance.
Enables polymorphism.
Example:
class Animal {
public void Eat() {
[Link]("Animal eats.");
}
}
class Dog : Animal {
public void Bark() {
[Link]("Dog barks.");
}
}
class Program {
static void Main() {
Dog dog = new Dog();
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
}
}
2. Types of Inheritance in C#:
1. SingleInheritance:
A single derived class inherits from a single base class.
class A { }
class B : A { }
2. HierarchicalInheritance:
Multiple derived classes inherit from the same base class.
class A { }
class B : A { }
class C : A { }
3. MultilevelInheritance:
A derived class inherits from another derived class.
class A { }
class B : A { }
class C : B { }
4. Multiple Inheritance (Not Supported in C#):
Achieved using interfaces.
[Link] in C#: An interface defines a contract that implementing classes must
follow.
It contains method signatures but no implementation.
Supports multiple inheritance.
Example:
interface IAnimal {
void Speak();
}
class Dog : IAnimal {
public void Speak() {
[Link]("Dog barks.");
}
}
class Program {
static void Main() {
IAnimal animal = new Dog();
[Link]();
}
}
Sol(b): Delegates and Events:
[Link] in C#:
A delegate is a type-safe function pointer that holds references to methods. It enables
methods to be called dynamically at runtime.
Steps to Use Delegates:
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
1. Define a delegate type.
2. Instantiate the delegate.
3. Invoke the method(s) via the delegate.
Example:
using System;
delegate void Message(string text);
class Program {
static void PrintMessage(string message) {
[Link]("Message: " + message);
}
static void Main() {
Message msg = PrintMessage; // Delegate points to PrintMessage
msg("Hello, World!");
}
}
[Link] in C#:
Events are special delegates used for notifying subscribers when something happens.
Commonly used for GUI applications (button clicks, etc.).
Steps to Use Events:
1. Declare an event based on a delegate.
2. Subscribe methods to the event.
3. Trigger the event.
Example:
using System;
delegate void Notify();
class Publisher {
public event Notify OnChange; // Declare an event
public void TriggerEvent() {
if (OnChange != null) OnChange(); // Invoke event
}
}
class Subscriber {
static void Main() {
Publisher pub = new Publisher();
// Subscribe to event
[Link] += () => [Link]("Event triggered!");
[Link](); // Trigger event
}
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Sol(c): arrays, Types of Arrays, and Lists in C#:
1. Arrays in C#:
Arrays are fixed-size, strongly-typed collections of elements stored in contiguous
memory.
Advantages: Fast access via index.
Syntax:
int[] arr = new int[5];
arr[0] = 10;
Types of Arrays:
1. Single-DimensionalArray:
Linear array where elements are accessed using a single index.
int[] arr = { 1, 2, 3, 4 };
2. Multi-DimensionalArray:
Two or more dimensions.
int[,] matrix = { { 1, 2 }, { 3, 4 } };
[Link](matrix[0, 1]); // Output: 2
3. JaggedArray:
Array of arrays, where sub-arrays can have different sizes.
int[][] jagged = new int[2][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
Example of Multi-Dimensional Array:
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i, j] + " ");
}
[Link]();
}
2. Lists in C#:
A dynamic collection in the [Link] namespace.
Unlike arrays, lists can grow or shrink dynamically.
Key Features of Lists:
Dynamic resizing.
Easy insertion and deletion.
Generic type support.
Example:
using System;
using [Link];
class Program {
static void Main()
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
{
List<int> numbers = new List<int> { 1, 2, 3 };
[Link](4); // Add an element
[Link](2); // Remove an element
foreach (int num in numbers) {
[Link](num);
}
}
}
Difference Between Arrays and Lists:
Aspect Array List
Size Fixed size after declaration. Dynamic resizing.
Performance Faster for fixed-size operations. Slight overhead for resizing.
Flexibility Requires manual resizing. Easily adds/removes elements.
Q 4. Answer any two parts of the following.
a) Write a short note on [Link] Providers? Explain details about the Accessing
Data bases using [Link] with an example?
b) Explain constructors and its types and show how to add constructor to the
building class.
c) Explain in details about the Data binding in windows forms and web forms?
SOL(a): [Link] Providers and Accessing Databases Using [Link]
1. [Link] Providers: [Link] providers are libraries that allow interaction with
different types of databases. They provide a consistent way to access data from SQL
databases, OLE DB, and XML.
Key [Link] Providers:
SQL Server Provider ([Link]): For SQL Server.
OLE DB Provider ([Link]): For legacy databases.
ODBC Provider ([Link]): For Open Database Connectivity.
Oracle Provider ([Link]): For Oracle databases.
Components of an [Link] Provider:
1. Connection: Manages the connection to the database.
2. Command: Executes SQL queries or stored procedures.
3. DataReader: Provides forward-only data access.
4. DataAdapter: Fills DataSet and updates the database.
2. Accessing Databases Using [Link]:
Establish a connection, execute queries, and fetch data.
Example: Fetching Data from a SQL Server Database
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
using System;
using [Link];
class Program {
static void Main() {
string connectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated
Security=True";
// Establish connection
using (SqlConnection conn = new SqlConnection(connectionString)) {
[Link]();
// SQL command
string query = "SELECT * FROM Students";
SqlCommand cmd = new SqlCommand(query, conn);
// Execute query and read data
SqlDataReader reader = [Link]();
while ([Link]()) {
[Link]($"ID: {reader["ID"]}, Name: {reader["Name"]}");
}
}
}
}
Explanation:
1. SqlConnection establishes a connection with the database.
2. SqlCommand executes the query.
3. SqlDataReader reads the data row by row.
Sol(b) Constructors and Their Types
[Link]: A constructor is a special method in a class that is automatically called
when an object of the class is created.
Used to initialize objects.
Constructor Name: Same as the class name.
No Return Type: Not even void.
2. Types of Constructors in C#:
a)Default Constructor: Automatically provided by C# if no constructor is defined.
class Example {
public Example() { // Default Constructor
[Link]("Default Constructor Called");
}
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
b) Parameterized Constructor: Accepts parameters for initializing fields.
class Example {
int x;
public Example(int value) { // Parameterized Constructor
x = value;
}
}
c)Copy Constructor: Initializes an object using another object.
class Example {
int x;
public Example(int value) { x = value; }
public Example(Example obj) { x = obj.x; } // Copy Constructor
}
d) Static Constructor: Initializes static fields and is called once, automatically.
class Example {
static Example() {
[Link]("Static Constructor Called");
}
}
[Link] a Constructor to a Building Class:
class Building {
string name;
int floors;
// Parameterized Constructor
public Building(string name, int floors) {
[Link] = name;
[Link] = floors;
}
public void ShowDetails() {
[Link]($"Building: {name}, Floors: {floors}");
}
}
class Program {
static void Main() {
Building building = new Building("Skyscraper", 50);
[Link](); // Output: Building: Skyscraper, Floors: 50
}
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Sol(c): Data Binding in Windows Forms and Web Forms
1. Data Binding Overview:
Definition: Linking UI elements to data sources like databases, XML files, or
objects.
Types:
o Simple Binding: Links a single control to a single data element.
o Complex Binding: Links a control to a data collection.
2. Data Binding in Windows Forms:
Used to display data in desktop applications.
Common controls for binding:
o TextBox, ComboBox, DataGridView.
Example: Binding Data to a DataGridView:
using System;
using [Link];
using [Link];
using [Link];
class Program : Form {
public Program() {
DataGridView dgv = new DataGridView { Dock = [Link] };
[Link](dgv);
string connectionString = "Data Source=.;Initial
Catalog=MyDatabase;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Students", conn);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt; // Bind DataTable to DataGridView
}
}
static void Main() {
[Link](new Program());
}
}
3. Data Binding in Web Forms:
Used to display data on web pages.
Common controls:
o GridView, DropDownList, Repeater.
Example: Binding Data to a GridView:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
using System;
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
using [Link];
using [Link];
public partial class WebForm1 : [Link] {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string connectionString = "Data Source=.;Initial
Catalog=MyDatabase;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Students", conn);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt; // Bind DataTable to GridView
[Link]();
}
}
}
}
Comparison of Windows Forms and Web Forms Data Binding:
Aspect Windows Forms Web Forms
Platform Desktop applications Web applications
DataGridView, ComboBox, GridView, DropDownList,
UI Controls
ListBox Repeater
State
Client-side Server-side
Management
Q 5. Answer any two parts of the following.
a) Write a short note on XML? Explain details about the Reading and Writing
XML. b) Explain in details about Creating and consuming AJAX?
c) Write the short note on the following.
I. Partial Classes and Methods.
II. Indexers.
Sol(a): XML (eXtensible Markup Language): A markup language designed to store
and transport data in a structured, human-readable, and machine-readable format.
Key Features:
o Platform-independent.
o Data is stored hierarchically using tags.
o Self-descriptive.
o Widely used in web services, configuration files, and data interchange.
Example of XML:
<Students>
<Student>
<ID>1</ID>
<Name>John Doe</Name>
</Student>
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
<Student>
<ID>2</ID>
<Name>Jane Smith</Name>
</Student>
</Students>
2. Reading XML in C#:
XML can be read using classes like XmlDocument, XmlReader, or LINQ to
XML.
Example Using XmlDocument:
using System;
using [Link];
class Program {
static void Main() {
XmlDocument doc = new XmlDocument();
[Link]("[Link]");
XmlNodeList students = [Link]("Student");
foreach (XmlNode student in students) {
[Link]($"ID: {student["ID"].InnerText}, Name:
{student["Name"].InnerText}");
}
}
}
3. Writing XML in C#:
XML can be created using XmlWriter or LINQ to XML.
Example Using XmlWriter:
using System;
using [Link];
class Program {
static void Main() {
using (XmlWriter writer = [Link]("[Link]")) {
[Link]();
[Link]("Students");
[Link]("Student");
[Link]("ID", "1");
[Link]("Name", "John Doe");
[Link]();
[Link]();
[Link]();
}
[Link]("XML File Created");
}
}
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
Sol(b): [Link] (Asynchronous JavaScript and XML): A web development
technique to create asynchronous web applications.
Key Features:
Updates parts of a web page without reloading the entire page.
Uses XMLHttpRequest or Fetch API for communication between the client and
server.
Commonly uses JSON or XML for data exchange.
2. Creating AJAX in Web Applications:
AJAX is implemented using JavaScript and server-side scripts (e.g., [Link],
PHP).
Example Using JavaScript:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function fetchData() {
const xhr = new XMLHttpRequest();
[Link]("GET", "[Link]", true);
[Link] = function () {
if ([Link] == 4 && [Link] == 200) {
[Link]("content").innerHTML =
[Link];
}
};
[Link]();
}
</script>
</head>
<body>
<button onclick="fetchData()">Fetch Data</button>
<div id="content"></div>
</body>
</html>
Explanation:
1. JavaScript sends a request to the server via XMLHttpRequest.
2. Server sends back a response (e.g., [Link] content).
3. The response is dynamically updated on the web page.
3. Consuming AJAX in [Link] Web Forms:
Server-Side Script Example:
using System;
using [Link];
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
public partial class Data : Page {
protected void Page_Load(object sender, EventArgs e) {
[Link]("Hello from Server!");
}
}
Client-Side Script Example:
<script>
function fetchServerData() {
fetch("[Link]")
.then(response => [Link]())
.then(data => [Link]("result").innerText = data);
}
</script>
<button onclick="fetchServerData()">Call Server</button>
<div id="result"></div>
Sol(c): I. Partial Classes and Methods
1. Partial Classes:
Definition: A feature in C# that allows splitting the definition of a class across
multiple files.
Purpose:
o Organize large classes.
o Separate auto-generated and developer-written code (common in tools
like Windows Forms).
Example: File 1 ([Link]):
partial class Example {
public void Method1() {
[Link]("Method1 from Part1");
}
}
File 2 ([Link]):
partial class Example {
public void Method2() {
[Link]("Method2 from Part2");
}
}
Usage:
Example obj = new Example();
obj.Method1();
obj.Method2();
2. Partial Methods:
Definition: A method declared in one part of a partial class and optionally
implemented in another part.
Rules:
o Must be void.
SHIVALIK COLLEGE OF ENGINEERING
Recognised under UGC Section (2f) of the UGC Act 1956
o The implementation is optional.
Example: File 1 ([Link]):
partial class Example {
partial void DisplayMessage();
}
File 2 ([Link]):
partial class Example {
partial void DisplayMessage() {
[Link]("Partial Method Implemented");
}
}
II. Indexers: Indexers allow objects to be accessed using array-like syntax.
Syntax:
public int this[int index] {
get { return array[index]; }
set { array[index] = value; }
}
Use Case: To access elements in a collection-like object.
2. Example of Indexers:
using System;
class MyCollection {
private string[] data = new string[5];
public string this[int index] {
get { return data[index]; }
set { data[index] = value; }
}
}
class Program {
static void Main() {
MyCollection collection = new MyCollection();
collection[0] = "Hello";
collection[1] = "World";
[Link](collection[0]); // Output: Hello
[Link](collection[1]); // Output: World
}
}
Advantages of Indexers:
Simplifies access to collection-like objects.
Enhances code readability