0% found this document useful (0 votes)
8 views

C Sharp

The document provides an overview of C# and .NET programming, detailing key components of the .NET Framework such as CLR and FCL, and explaining concepts like string literals, structures, objects, and classes. It also covers advanced topics including ADO.NET, serialization, transactions, marshaling, and remoting configuration. Additionally, it discusses arrays, conditional statements, and the advantages of stored procedures.

Uploaded by

carryop7755
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Sharp

The document provides an overview of C# and .NET programming, detailing key components of the .NET Framework such as CLR and FCL, and explaining concepts like string literals, structures, objects, and classes. It also covers advanced topics including ADO.NET, serialization, transactions, marshaling, and remoting configuration. Additionally, it discusses arrays, conditional statements, and the advantages of stored procedures.

Uploaded by

carryop7755
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

C# and .

Net programming
PART – A
1. Summarize the .NET framework components.

The .NET Framework, primarily used with C#, consists of two key components:
The Common Language Runtime (CLR) which manages code execution across
different languages, and the .NET Framework Class Library (FCL) which provides a
large set of pre-built classes and functions for developers to use when building
applications, allowing for cross-language interoperability and a consistent
development experience across various types of applications.

1. Common Language Runtime (CLR):


 Executes .NET applications.
 Manages memory, security, and exception handling.

2. .NET Framework Class Library:


 A large collection of pre-built classes and functions.
 Supports various programming tasks like file handling, database access, and web services.

3. Assemblies:
 Compiled code libraries (DLLs or EXEs).
 Contain code and resources for .NET applications.

4. Windows Forms:
 A set of classes for building desktop applications.
 Provides a user interface framework.

5. ASP.NET:
 A framework for building web applications and services.
 Supports dynamic web content and web APIs.
2. Write short notes on string Literal in C#.

String Literal in C#
Definition
A string literal is a sequence of characters enclosed in double quotes. It is used to
represent a string value in C# code.
Example
string name = "John Doe";
In this example, "John Doe" is a string literal.
Types of String Literals
Single-Line String Literal
A single-line string literal is a sequence of characters enclosed in double quotes on a
single line.
string name = "John Doe";
Multi-Line String Literal
A multi-line string literal is a sequence of characters enclosed in double quotes that
spans multiple lines. To create a multi-line string literal, you can use the @ symbol
before the string.
string address = @"123 Main St
Anytown, USA
12345";
Escape Sequences
Escape sequences are used to represent special characters in a string literal. Here are
some common escape sequences:
- \\ (backslash)
- \" (double quote)
- \n (new line)
- \t (tab)
Verbatim Literal
A verbatim literal is a string literal that ignores escape sequences. To create a
verbatim literal, you can prefix the string with the @ symbol.
string path = @"C:\Windows\System32";
In this example, the @ symbol tells the compiler to ignore the backslash escape
sequences, so the string is treated as a literal path.
3. Give a brief note on structure concept.

In C#, a structure (or struct) is a value type that allows you to combine multiple variables of
different data types into a single unit.
Characteristics of Structures:
1. Value type: Structures are value types, not reference types.
2. Composite data type: Structures can contain multiple variables of different data types.
3. Memory allocation: Structures are stored on the stack, not on the heap.
4. No inheritance: Structures cannot inherit from other structures or classes.
5. No null reference: Structures cannot be null.
Declaring a Structure:
public struct Person
{
public string Name;
public int Age;
public string Address;
}
Using a Structure:
Person person;
person.Name = "John Doe";
person.Age = 30;
person.Address = "123 Main St";
Types of Structures:
1. Simple structure: Contains only variables.
2. Nested structure: Contains another structure.
3. Array structure: Contains an array.
Structure Members:
1. Fields: Variables declared inside a structure.
2. Properties: Provide getter and setter access to fields.
3. Methods: Perform operations on structure data.
4. Constructors: Initialize structure fields.
5. Events: Notify changes to structure data.

4. Define an object. What are the uses of class?

Definition of Object:
An object is an instance of a class, representing a real-world entity or concept. It has its own set
of attributes (data) and methods (functions) that describe and define its behaviour. Objects are
the building blocks of object-oriented programming (OOP).
Characteristics of Objects:
1. Identity: Unique identity.
2. State: Attributes or data.
3. Behaviour: Methods or functions.
4. Interactions: Communication with other objects.
Example:
// Class: Car
public class Car {
// Attributes (data)
string color;
int speed;

// Methods (functions)
void accelerate() { ... }
void brake() { ... }
}

// Object: myCar (instance of Car class)


Car myCar = new Car();
myCar.color = "Red";
myCar.speed = 60;
myCar.accelerate();
Use of Class:
A class is a blueprint or template that defines the properties and behavior of an object.
Common Uses of Classes:
1. Modelling real-world entities (e.g., customers, products).
2. Creating data structures (e.g., arrays, linked lists).
3. Implementing algorithms (e.g., sorting, searching).
4. Building graphical user interfaces (GUIs).
5. Simulating complex systems (e.g., games, simulations).
6. Managing databases.
7. Creating network applications.
8. Developing web applications.
Types of Classes:
1. Concrete class: A complete class with implementation.
2. Abstract class: A partial class with abstract methods.
3. Interface: A contract specifying methods.
4. Nested class: A class inside another class.
5. Static class: A class with only static members.

5. List down the common property in .NET Framework

Some common properties of the .NET Framework include:


 Language interoperability: Allows code written in different programming languages to interact
with each other
 Portability: Compiles source code into machine-independent code, making it portable
 Security: Verifies applications before giving users access to them
 Language independence: Supports multiple programming languages, such as C#, F#, and VB.NET
 Common Type System (CTS): A standard that defines how type definitions and values are
represented in computer memory

General Properties

 Length: Used often in arrays, strings, collections, etc.

string example = "Hello";


int length = example.Length;

 Count: Used in collections like lists, dictionaries, etc.

List<int> numbers = new List<int>{1, 2, 3};


int count = numbers.Count;

 Name: Common in classes, especially in UI controls.

Button button = new Button();


button.Name = "submitButton";

6. Define Polymorphism and list out its types.

 Definition: Ability of a method to perform different tasks based on the object type.

Types of Polymorphism

1. Compile-Time Polymorphism

(Static Binding):
 Method Overloading: Same method name, different parameters.
 Operator Overloading: Custom behavior for operators.
class Example {
public void Show(int a) { Console.WriteLine("Int: " + a); }
public void Show(string a) { Console.WriteLine("String: " + a); }
}

2. Runtime Polymorphism

(Dynamic Binding):
 Method Overriding: Derived class redefines a base class method.
class Base {
public virtual void Show() { Console.WriteLine("Base Class"); }
}
class Derived : Base {
public override void Show() { Console.WriteLine("Derived Class"); }
}
7. List out the advantages of stored procedures.

What is a Stored Procedure?


A stored procedure is a precompiled SQL program that performs a specific task or set of
tasks. It is stored in a database and can be executed repeatedly, reducing the need to
rewrite and recompile the same code.
1. Performance - Faster execution
2. Security - Protects against SQL injection
3. Maintenance - Easier to update
4. Reusability - Can be reused across applications
5. Reduced Network Traffic - Fewer calls to the database
6. Transaction Control - Better management of transactions
7. Consistency - Ensures uniform data handling

8. Define and give a note on ADO .Net model.

Definition: ADO.NET is a data access technology in the .NET Framework that enables
applications to interact with databases.
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["Username"]);
}
}

 Key Components:
 Connection: Establishes a connection to the database.
 Command: Executes SQL queries or stored procedures.
 DataReader: Provides a way to read a forward-only stream of data from the database.
 DataSet: In-memory representation of data that can hold multiple tables and relationships.
 DataAdapter: Bridges the DataSet and the database, filling the DataSet with data and updating
the database.

9. Write a short note on data adapter.

Definition:

A Data Adapter is a bridge between a Data Set and a data source, facilitating the retrieval
and updating of data.

Key Functions:
a. Fill: Populates a Data Set or Data Table with data from the database.
b. Update: Sends changes made in the Data Set back to the database.

Components:
c. Select Command: SQL command to retrieve data.
d. Insert Command: SQL command to insert new data.
e. Update Command: SQL command to update existing data.
f. Delete Command: SQL command to delete data.
10. Write short note on web .configuration.

Definition:
Web configuration is the process of setting up and managing the configuration
settings for a web application.
Web Configuration in C#
1. File: Web.config
2. Purpose:
 Store application settings
 Database connections
 Security settings
3. Key Sections:
 appSettings
 connectionStrings
 system.web
4. Access:
 ConfigurationManager
 WebConfigurationManager

11. Describe the serialization and its process.

1. Definition

 Serialization: Converting an object's state to a format that can be stored or transmitted.


2. Purpose

 Save or transmit object data.

Serialization Process

1. Serialization

1. Create an object: Instantiate the object you want to serialize.


2. Convert object state to a stream: Transform the object into a stream format (e.g., XML, JSON).
3. Save or transmit the stream: Store the stream in a file or send it over a network.

2. Deserialization

1. Receive or read the stream: Obtain the serialized stream.


2. Convert the stream back to an object: Transform the stream back into the original object.
3. Use the recreated object: Access or manipulate the object as needed.

Serialization Types

1. Binary Serialization: Serializes objects to a binary format.


2. XML Serialization: Serializes objects to an XML format.
3. JSON Serialization: Serializes objects to a JSON format.

12. State the phases of a transaction

Definition of a Transaction in C#

 Transaction: A sequence of operations treated as a single unit of work.

Phases of a Transaction in C#

1. Begin:
 Start the transaction.

2. Prepare:
 Check if all operations are ready to commit.

3. Commit:
 Apply all changes permanently.
4. Rollback:
 Undo changes if an error occurs.

5. Complete:
 End the transaction and clean up resources.

13. Narrate the techniques of producing an assembly?

Techniques for Producing an Assembly

1. Types of Assemblies:
 Private
 Shared
 Satellite

2. Creation:
 Visual Studio: New Project → Class Library/Console App → Build
 Command Line: csc /target:library MyClass.cs

3. Assembly Manifest:
 Metadata (version, culture, public key)

4. Versioning:
 AssemblyVersion("1.0.0.0")

5. Strong Naming:
 Generate Key: sn -k MyKey.snk
 Apply Key: AssemblyKeyFile("MyKey.snk")

6. Resources:
 Embed images/strings

7. Deployment:
 Install to GAC: gacutil -i MyAssembly.dll

8. Reflection:
 Inspect and load types at runtime
14. Enumerate Marshaling and describe its types.
Marshaling
1. Definition: Converting data types between managed and unmanaged code.
2. Purpose: Enables communication between .NET code and native code.

Types of Marshaling
1. Blittable Marshaling:
1. Definition: Directly copying data between managed and unmanaged code.
2. Examples: Integers, floats, and structs containing blittable types.

2. Non-Blittable Marshaling:
1. Definition: Converting data types between managed and unmanaged code.
2. Examples: Strings, arrays, and classes.

3. Implicit Marshaling:
1. Definition: Automatic conversion of data types.
2. Examples: Calling native functions from .NET code.

4. Explicit Marshaling:
1. Definition: Manual conversion of data types using attributes or APIs.
2. Examples: Using MarshalAs attribute or Marshal class.

15. List out the information stored in the configuration file for remoting.

A .NET remoting configuration file stores details about how a remote object can be accessed by
clients, including:
 Object details:
Which classes are allowed to be accessed remotely (their names and assembly information).

 Channel information:
The communication channel used to reach the remote object (like HTTP, TCP) and its port
number.
 URL:
A unique address to identify the remote object on the server.
 Activation mode:
How the remote object should be created (e.g., automatically when a client requests it, or
manually on the server).
 Lifetime policies:
How long a remote object should live before being automatically removed (lease time, renewal
settings).

16 marks :
1. What is an array? Discuss array class with suitable example
What is an Array?
An array is a collection of elements of the same data type stored in contiguous memory
locations.
It allows you to store multiple values under a single variable name.

Array Class in C#
The Array class in C# is a built-in class that provides various methods for manipulating arrays.
Array Declaration

type[] arrayName = new type[length];

Example Program:
using System;
class ArrayExample
{
static void Main()
{
// Declare and initialize an integer array
int[] scores = { 90, 80, 70, 60, };
// Print array elements
Console.WriteLine("Array Elements:");
foreach (int score in scores)
{
Console.WriteLine(score);
}
// Get array length
Console.WriteLine("\nArray Length: " + scores.Length);
// Access specific array element
Console.WriteLine("\nElement at index 2: " + scores[2]);
}
}

Output:

Array Elements:
90
80
70
60
Array Length: 5
Element at index 2
Array Class Methods:
Some commonly used methods of the Array class include:
- Length:
Gets the number of elements in the array.
- Rank:
Gets the number of dimensions in the array.
- GetValue():
Gets the value at a specified index.
- SetValue():
Sets the value at a specified index.
- Sort():
Sorts the array elements.
- Reverse():
Reverses the order of array elements.
Types of Arrays:
- Single-dimensional arrays: Stores elements in a linear sequence.
e.g., int[] scores
- Multi-dimensional arrays: Stores elements in a tabular structure.
e.g., int[,] matrix
- Jagged arrays: An array of arrays with different lengths.
(e.g., int[][] jagged Array)

2. Elaborate the conditional statement with suitable program.


Conditional Statements in C#

1. If Statement

The if statement checks a condition and executes a block of code if the condition is true.
Example:

using System;

class Program
{
static void Main()
{
int number = 10;

if (number > 0)
{
Console.WriteLine("The number is positive.");
}
}
}
Output:

The number is positive.

This diagram represents the basic flow of an if statement:


1. Start: The program begins execution.
2. Condition?: The condition is evaluated.
3. Yes: If the condition is true, the code block is executed.
4. No: If the condition is false, the code block is skipped.
5. End: The program continues after the if statement.
2. If-Else Statement

The if-else statement allows you to execute one block of code if the condition is true and
another block if it is false.

Example:

using System;

class Program
{
static void Main()
{
int number = -5;

if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is not positive.");
}
}
Output:
The number is not positive.
Explanation of the Flow Diagram:
1. Start: The program begins execution.
2. Condition?: The condition of the if statement is evaluated.
 Yes: If true, execute the corresponding code block.
 No: If false, execute the else code block.
3. End: The program continues after the if-else statement.

3. Else If Statement

You can chain multiple conditions using else if.

Example:

using System;

class Program
{
static void Main()
{
int number = 0;

if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}
}
}
Output:

The number is zero.


Explanation of the Flow Diagram:

1. Start: The program begins execution.


2. Condition 1?: The first condition is evaluated.
 Yes: If true, execute Code Block 1.
 No: Proceed to Condition 2.
3. Condition 2?: The second condition is evaluated.
 Yes: If true, execute Code Block 2.
 No: Proceed to Condition 3.
4. Condition 3?: The third condition is evaluated.
 Yes: If true, execute Code Block 3.
 No: Execute Code Block 4 (default case).
5. End: The program continues after the else if statement.
4. Switch Statement

The switch statement is used when you have multiple conditions based on the same variable.

Example:

using System;

class Program
{
static void Main()
{
int day = 3;

switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
}
}
Output:

Wednesday
Explanation of the Flow Diagram:

1. Start: The program begins execution.


2. Evaluate Expression: The expression in the switch statement is evaluated.
3. Case 1?: Check if the value matches Case 1.
 Yes: If true, execute Case 1 code block.
 No: Proceed to Case 2.
4. Case 2?: Check if the value matches Case 2.
 Yes: If true, execute Case 2 code block.
 No: Proceed to Case 3.
5. Case 3?: Check if the value matches Case 3.
 Yes: If true, execute Case 3 code block.
 No: Proceed to Default Case.
6. Default Case?: Check if the default case should be executed.
 Yes: Execute Default code block.
 No: Skip to the end.
7. End: The program continues after the switch statement.

3. Explain in detail about the types of operators.

Operators are special symbols or keywords used to perform operations on data


(variables and values).

Operators can be divided into several types based on their functionality. Let's explore
the types of operators in C# with simple examples:
1. Arithmetic Operators

These are used for basic mathematical operations.

Arithmetic operators are used to perform mathematical calculations in C#.

They include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

These operators allow us to manipulate numerical values and perform calculations with ease.

For example, if we want to add two numbers together, we can simply use the addition operator
(+).

Operator Description Example


+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus a % b (remainder)

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10, b = 3;
Console.WriteLine("Addition: " + (a + b));
Console.WriteLine("Subtraction: " + (a - b));
Console.WriteLine("Multiplication: " + (a * b));
Console.WriteLine("Division: " + (a / b));
Console.WriteLine("Modulus: " + (a % b));
}
}

Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1
2. Relational (Comparison) Operators

These compare two values and return true or false.

Comparison operators are used to compare values in C#.

They include == (equality), != (inequality), > (greater than), < (less than), >= (greater than or
equal to), and <= (less than or equal to).

These operators return a Boolean value (true or false) based on the comparison result.

For example, if we want to check if two numbers are equal, we can use the equality operator
(==).

Operator Description Example


== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or equal a >= b
<= Less or equal a <= b

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10, b = 5;
Console.WriteLine("Equal: " + (a == b));
Console.WriteLine("Not Equal: " + (a != b));
Console.WriteLine("Greater: " + (a > b));
Console.WriteLine("Less: " + (a < b));
}
}

Output:

Equal: False
Not Equal: True
Greater: True
Less: False
3. Logical Operators

These are used to combine multiple conditions.

Logical operators are used to perform logical operations in C#. They include && (logical AND),
|| (logical OR), and ! (logical NOT).

These operators are commonly used in conditional statements and loops.

They allow us to combine multiple conditions and control the flow of our program based on the
result.

For instance, if we want to check if both condition A and condition B are true, we can use the
logical AND operator (&&).

Operator Description Example


&& Logical AND a > 5 && b < 10
|| Logical OR a == b || c != d

! Logical NOT !(a > 5)

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10, b = 3;
Console.WriteLine("AND: " + (a > 5 && b < 5));
Console.WriteLine("OR: " + (a > 5 || b > 5));
Console.WriteLine("NOT: " + !(a > 5));
}
}

Output:

AND: True
OR: True
NOT: False
4. Bitwise Operators

These work on binary data.

Bitwise operators are used to perform operations at the bit level in C#.

They include &, |, ^, ~, <<, and >>.

These operators manipulate individual bits of an operand, allowing us to perform operations


such as bitwise AND, bitwise OR, bitwise XOR, bitwise complement, left shift, and right shift.

Bitwise operators are particularly useful in scenarios where we need to work with binary data
or perform low-level operations.

Operator Description Example


& AND a & b
|| OR a || b
^ XOR a ^ b
~ Complement ~a
<< Left Shift a << 1
>> Right Shift a >> 1

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 5, b = 3; // Binary: a = 0101, b = 0011
Console.WriteLine("AND: " + (a & b));
Console.WriteLine("OR: " + (a | b));
Console.WriteLine("XOR: " + (a ^ b));
Console.WriteLine("Left Shift: " + (a << 1));
Console.WriteLine("Right Shift: " + (a >> 1));
}
}

Output:

AND: 1
OR: 7
XOR: 6
Left Shift: 10
Right Shift: 2
5. Assignment Operators

These assign values to variables.

Assignment operators are used to assign values to variables in C#.

They include the simple assignment operator (=), as well as compound assignment operators
such as +=, -=, *=, and /=.

These operators not only assign values but also perform an operation simultaneously.

For instance, the += operator adds the right-hand operand to the left-hand operand and assigns
the result to the left-hand operand.

Operator Description Example


= Assign a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10, b = 5;
a += b; // a = a + b
Console.WriteLine("Add and assign: " + a);

a -= b; // a = a - b
Console.WriteLine("Subtract and assign: " + a);
}
}

Output:

Add and assign: 15


Subtract and assign: 10
6. Unary Operators

These operate on a single operand.

Unary operators are used to perform operations on a single operand in C#.

They include ++ (increment), -- (decrement), + (positive), - (negative), ! (logical NOT), and ~


(bitwise complement).

These operators allow us to modify the value of a variable or change its state based on specific
conditions.

For example, the increment operator (++) increases the value of a variable by 1.

Operator Description Example


+ Positive +a
- Negative -a
++ Increment a++
-- Decrement a--

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10;
Console.WriteLine("Initial: " + a);
Console.WriteLine("Increment: " + (++a));
Console.WriteLine("Decrement: " + (--a));
}
}

Output:

Initial: 10
Increment: 11
Decrement: 10
7. Ternary Operator

This is a shorthand for if-else.

Ternary operators are unique to C# and allow us to write concise conditional expressions.

The ternary operator (?:) takes three operands: a condition, a true expression, and a false
expression.

It evaluates the condition and returns the true expression if the condition is true, otherwise, it
returns the false expression.

Ternary operators are handy when we need to assign a value to a variable based on a condition
in a single line of code.

Types:

1. Basic Ternary Operator: Evaluates a condition and returns one of two values.

2. Nested Ternary Operator: Ternary operators can be nested for multiple conditions.

Operator Description Example


?: Conditional a > b ? x : y

Example Program:

csharp
using System;

class Program
{
static void Main()
{
int a = 10, b = 5;
string result = (a > b) ? "a is greater" : "b is greater";
Console.WriteLine(result);
}
}

Output:

a is greater
4. Briefly discuss about methods and its types with suitable program.

What are Methods in C#?

 A method is a block of code that performs a specific task.


 It helps organize code, avoid repetition, and make programs easy to read.
 Methods can:
o Take input values (parameters).
o Return a value or perform a task without returning anything.

A method is a block of code that performs a specific task. It helps organize code, avoid
repetition, and makes it easier to understand and maintain.

 Create a Method: Write a method definition.


 Call a Method: Use the method name to execute it.

1. How to Create and Call a Method

Steps:

 Create: Define the method inside a class using a specific syntax.


 Call: Use the method's name inside the Main() method or another method.

Example: Create and Call a Method:


csharp
using System;

class Program
{
// Create a method
void SayHello()
{
Console.WriteLine("Hello from the method!");
}

static void Main()


{
// Create an object to call the method
Program obj = new Program();
obj.SayHello(); // Call the method
}
}
Output:

Hello from the method!

1. Static Method

 Belongs to the class and can be called without creating an object.


 Used for tasks that don't depend on instance variables.

Example Program:

csharp
using System;

class Program
{
static void Greet()
{
Console.WriteLine("Hello from the static method!");
}

static void Main()


{
Greet(); // Calling the static method
}
}

Output:

Hello from the static method!

2. Instance Method

 Belongs to an object and requires an object to call.


 Used when the method works with instance variables.

Example Program:
csharp
using System;

class Program
{
void ShowMessage()
{
Console.WriteLine("This is an instance method.");
}

static void Main()


{
Program obj = new Program(); // Create an object
obj.ShowMessage(); // Call the instance method
}
}

Output:

This is an instance method.

3. Void Method

 Does not return any value; it only performs a task.

Example Program:

csharp
using System;

class Program
{
void PrintMessage()
{
Console.WriteLine("This is a void method, it doesn't
return anything.");
}

static void Main()


{
Program obj = new Program();
obj.PrintMessage(); // Call the void method
}
}
Output:

This is a void method, it doesn't return anything.

4. Return-Type Method

 Returns a value (e.g., int, string, etc.) to the caller.

Example Program:

csharp
using System;

class Program
{
int AddNumbers(int a, int b)
{
return a + b; // Return the sum
}

static void Main()


{
Program obj = new Program();
int result = obj.AddNumbers(5, 7); // Call the method
and store the result
Console.WriteLine("Sum: " + result);
}
}

Output:

Sum: 12

5. Parameterized Method

 Takes input values (parameters) to perform operations.

Example Program:
csharp
using System;

class Program
{
void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}

static void Main()


{
Program obj = new Program();
obj.Greet("Alice"); // Call with a parameter
}
}

Output:

Hello, Alice!

6. Non-Parameterized Method

 Does not take any inputs; it performs a task without requiring parameters.

Example Program:

csharp
using System;

class Program
{
void DisplayMessage()
{
Console.WriteLine("This is a non-parameterized
method.");
}

static void Main()


{
Program obj = new Program();
obj.DisplayMessage(); // Call without parameters
}
}
Output:

This is a non-parameterized method.

Summary Table

Method Type Description Example

Static Method Belongs to the class. Greet()

Instance Method Belongs to an object. ShowMessage()

Void Method Does not return a value. PrintMessage()

Return-Type Method Returns a value. AddNumbers()

Parameterized Method Takes input values (parameters). Greet("Alice")

Non-Parameterized Does not take input values. DisplayMessage()

Declaring a Method in C#

 Access Modifier: Defines the visibility (public, private, etc.) of the method.
 Return Type: Specifies the data type the method returns or 'void' for no return.
 Method Name: Unique identifier for the method.
 Parameters: Input values the method accepts (optional).
 Body: Contains the method's code logic enclosed in curly braces {}.

5. Describe the architecture of .NET framework with neat diagram

Architecture of .NET Framework


The .NET Framework is a software development platform developed by Microsoft. It provides a
runtime environment and libraries for building and running applications. Its architecture
consists of several key components.

What is the .NET Framework?

The .NET Framework is a development platform by Microsoft used for creating Windows
applications, web applications, and services. It provides tools, libraries, and a runtime to make
coding faster and easier.

Components of .NET Framework

1. Common Language Runtime (CLR):


o The execution engine for .NET applications.
o Manages memory, handles exceptions, and provides security.
o Includes Just-In-Time (JIT) compiler for converting MSIL (Intermediate Language)
to native code.
2. Base Class Library (BCL):
o A collection of reusable classes and APIs.
o Provides functionality for tasks like file handling, database operations,
networking, etc.
3. Application Development Frameworks:
o Includes frameworks for building specific types of applications:
 ASP.NET: For web applications.
 Windows Forms: For desktop GUI applications.
 WPF (Windows Presentation Foundation): For advanced UI design.
 ADO.NET: For database access.
4. Common Type System (CTS):
o Defines rules for data types to ensure interoperability between languages.
5. Common Language Specification (CLS):
o A subset of rules that all .NET languages must follow to ensure compatibility.
6. Metadata and Assemblies:
o Metadata: Information about the program, such as types and methods.
o Assemblies: Deployable units of compiled code (DLLs or EXEs).
7. .NET Languages:
o Supports multiple programming languages like C#, VB.NET, and F#.
o All languages share the same runtime environment and libraries.
8. Class Loader:
o Loads classes for execution.
9. Framework Class Library (FCL)
o A broader collection of libraries for application development.
10. Languages
o Supports multiple languages like C#, VB.NET, and F#.
o All languages compile to a common Intermediate Language (IL) for execution.
11. Assemblies

o Compiled code files (.DLL or .EXE) with metadata for versioning and deployment.

Features
 Cross-language interoperability: Allows code written in different languages to work together
 Automatic resource management: Manages resources automatically
 Debugging support: Provides rich debugging support
 Security: Provides security features
 Tool support: Provides tool support
 Portability: Makes the framework portable

Advantages of .NET Framework:

1. Supports Multiple Languages: Choose any supported language for development.


2. Robust Security: Built-in features for secure app development.
3. Prebuilt Libraries: Save time with reusable code in the BCL.
4. Memory Management: Reduces memory errors with automatic garbage collection.
5. Backward Compatibility: Multiple framework versions can run side-by-side.
6. Powerful Tools: Use Visual Studio for streamlined development.
7. Large Community: Vast resources and support available.

Disadvantages of .NET Framework

1. Windows Dependency: Primarily works on Windows systems.


2. High Memory Usage: Applications may require more resources compared to native apps.
3. Limited Cross-Platform Support: Earlier versions are not cross-platform (resolved in .NET Core).
4. Cost of Development Tools: Tools like Visual Studio can be expensive for some users.
5. Version Compatibility Issues: Older applications may face challenges running on new
framework versions.

6. Explain while and do-while concepts with an example program

Looping in a programming language is a way to execute a statement or a set of


statements multiple times depending on the result of the condition to be
evaluated to execute statements.
The result condition should be true to execute statements within loops.
Looping in C# allows you to execute a block of code repeatedly based on a
condition.
C# supports multiple types of loops to suit different scenarios.

1. while Loop

 Condition Check: Evaluates the condition before executing the loop body.
 Execution: If the condition is false initially, the loop body does not run.
 Use Case: Ideal when the number of iterations is not known.
Concept

 The while loop checks the condition before executing the loop body.
 If the condition is false initially, the loop will not run.

Syntax in C#

csharp
while (condition) {
// Code to execute while the condition is true
}

Example Program

csharp
using System;

class Program
{
static void Main()
{
int i = 1; // Initialization
while (i <= 5) // Condition
{
Console.WriteLine($"while loop iteration: {i}");
i++; // Increment
}
}
}

Output

while loop iteration: 1


while loop iteration: 2
while loop iteration: 3
while loop iteration: 4
while loop iteration: 5

2. do-while Loop

 Condition Check: Evaluates the condition after executing the loop body.
 Execution: The loop body always runs at least once, even if the condition is false.
 Use Case: Useful when you want the loop to execute at least once.

Concept

 The do-while loop ensures the loop body executes at least once, as the condition is
checked after executing the loop body.
Syntax in C#

csharp
do {
// Code to execute
} while (condition);

Example Program

csharp
using System;

class Program
{
static void Main()
{
int i = 1; // Initialization
do
{
Console.WriteLine($"do-while loop iteration: {i}");
i++; // Increment
} while (i <= 5); // Condition
}
}
Output

do-while loop iteration: 1


do-while loop iteration: 2
do-while loop iteration: 3
do-while loop iteration: 4
do-while loop iteration: 5

Key Difference Between while and do-while

Feature while Loop do-while Loop

Condition Check Before the loop body After the loop body execution
execution

Guaranteed May not execute if the Executes at least once, even if the
Execution condition is false condition is false

7. Define Exceptions handled in C#? List out its types with suitable program.

Exceptions in C#

 Definition: Exceptions are runtime errors that disrupt the normal flow of program
execution.
 Purpose: They provide a mechanism to handle unexpected situations like invalid user
input, file not found, network issues, etc.
 Benefits:
o Error Handling: Gracefully handle errors instead of abrupt program termination.
o Maintainability: Improve code readability and maintainability by separating
error handling logic.
o Robustness: Create more robust and reliable applications.

Types of Exceptions in C#

System Exception: Base class for predefined exceptions.


Application Exception: A base class for user-defined exceptions.
Divide By Zero Exception: Raised when attempting to divide a number by zero.
Null Reference Exception: Occurs when trying to access an object that is null.
File Not Found Exception: Happens when a file is not found.
Index Out Of Range Exception: Happens when accessing an invalid index in an array or
collection.

Argument Exception: Raised when an invalid argument is passed to a method.

 System.Exception: The base class for all exceptions.


 System.ArithmeticException: For arithmetic errors like division by zero

(int result = 10 / 0;).

 System. Null Reference Exception: Occurs when trying to access a member of a null
object .

(string str = null; Console.WriteLine(str.Length);).

 System. Invalid Operation Exception: Thrown when an invalid operation is attempted.

(Stack<int> stack = new Stack<int>(); stack.Pop(); // Stack is empty).

 System. IO Exception: Base class for input/output exceptions like file not found.

(File.ReadAllText("nonexistent.txt");).

 System. Argument Exception: Thrown when an invalid argument is passed to a method.

(int.Parse("abc");).

 System. Index Out Of Range Exception: Thrown when an array index is out of bounds.

(int[] arr = { 1, 2, 3 }; Console.WriteLine(arr[5]);).

 System. Format Exception: Thrown when a string cannot be parsed to the desired type.

(int.Parse("12.3");).

Handling Exceptions with try-catch-finally

 try block: Encloses the code that might throw an exception.


 catch block: Handles the specific exception type.
 finally block: (Optional) Code that executes regardless of whether an exception
occurred or not.
Example:

using System;

public class ExceptionHandlingExample


{
public static void Main(string[] args)
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Index out of bounds
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range: " + ex.Message);
}
finally
{
Console.WriteLine("Finally block executed.");
}
}
}

This program will output:

Index out of range: Index was outside the bounds of the array.
Finally block executed.

C# has provided necessary built-in exception classes to handle all the exceptions in our applications, and all
exception classes are derived from the base class called Exception.
The Exception class will identify the exception type and provide the properties that have details about the
exception.

In c#, the Exception class further classified into two other classes called
System Exception
Application Exception

System Exception: is a base class for all CLR generated errors.

Application Exception is a base class for all application-related exceptions.

The following diagram will illustrate more details about the exception classes in c#.

If you observe the above diagram, the System Exception is a base class for all CLR exceptions,
and these will occur during the program's execution.
The Application Exception is a base class for application-related exceptions, and we can derive
this class from creating our own exception classes.

C# Exception Classes
The following table lists some of the important exception classes available in c#.
Ex Exceptionception Des Descriptioncription

AccessViolationException This exception will raise when there is an attempt to read or write
protected memory.

ArgumentException This exception will be thrown when one of the arguments provided to a
method is not valid.

ArgumentNullException This exception will occur when a null argument is passed to a method
that does not accept it as a valid argument.

ArgumentOutOfRangeException This exception will occur when the value of an argument is outside the
allowable range of values.

ArithmeticException This exception will occur for errors in arithmetic, casting, or conversion
operation.

DivideByZeroException This exception will occur when we try to divide an integral or decimal
value by zero.

FormatException This will occur when the format of an argument is invalid.

IndexOutOfRangeException This will occur when we try to access an element of an array or collection
with an index outside of its bounds.

InvalidCastException This exception occurs for invalid casting or explicit conversion.

NullReferenceException This exception will occur when we try to reference an object of NULL
type.

OutOfMemoryException This will occur when the program is not having enough memory to
execute the code.

OverflowException This will occur when arithmetic, casting, or conversion operation results
in an overflow.

StackOverflowException This exception will occur when the execution stack overflows.

TimeoutException This will occur when the time allotted for a process or operation has
expired.

8. Articulate the concept of constructors and its types.

Constructors in C#: A constructor is a special method in a class that is called when an object of
that class is instantiated. It has the same name as the class and no return type, not even void. A
constructor is a special method used to initialize objects when they are created. It allocates
memory for the object and sets initial values for its attributes. Constructors have the same
name as the class and no return type.

Features of Constructors:
o Constructors initialize object attributes during object creation.
o They have the same name as the class.
o Constructors don’t have a return type.
o They ensure proper object setup.

Types of Constructors

1. Default Constructor

 A constructor with no parameters.


 Used to initialize objects with default values.

Example Program:

public class Student


{
public string Name { get; set; }

public Student() // Default Constructor


{
Name = "Unknown";
}
}

class Program
{
static void Main()
{
Student student = new Student();
Console.WriteLine(student.Name); // Output: Unknown
}
}

Output:

Unknown

2. Parameterized Constructor

 A constructor with one or more parameters.


 Used to initialize objects with specific values.

Example Program:
public class Student
{
public string Name { get; set; }

public Student(string name) // Parameterized Constructor


{
Name = name;
}
}

class Program
{
static void Main()
{
Student student = new Student("John Doe");
Console.WriteLine(student.Name); // Output: John Doe
}
}

Output:

John Doe

3. Copy Constructor

 A constructor that takes an object of the same class as a parameter.


 Used to create a copy of an existing object.

Example Program:

public class Student


{
public string Name { get; set; }

public Student(Student student) // Copy Constructor


{
Name = student.Name;
}
public Student(string name) // Parameterized Constructor
{
Name = name;
}
}

class Program
{
static void Main()
{
Student student1 = new Student("John Doe");
Student student2 = new Student(student1); // Copying student1
Console.WriteLine(student2.Name); // Output: John Doe
}
}
Output:

John Doe

4. Static Constructor

 A constructor that is called automatically before the first instance of a class is created or
any static member is accessed.
 Used to initialize static members of a class.

Example Program:

public class Student


{
public static string SchoolName { get; set; }

static Student() // Static Constructor


{
SchoolName = "ABC School";
}

public Student(string name) // Parameterized Constructor


{
Name = name;
}

public string Name { get; set; }


}

class Program
{
static void Main()
{
Console.WriteLine(Student.SchoolName); // Output: ABC School
}
}

Output:

ABC School

5. Private Constructor

 A constructor with private access, preventing object creation from outside the class.
 Typically used for singleton design patterns.
public class Singleton
{
private static Singleton _instance;

private Singleton() { } // Private Constructor

public static Singleton GetInstance()


{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}

class Program
{
static void Main()
{
Singleton obj = Singleton.GetInstance();
Console.WriteLine("Singleton instance created.");
}
}

Outputs:

Singleton instance created.


9. Describe the concept of a)Indexers b) Interface.

a) Indexers `

 🔑 Definition: Indexers allow instances of a class or struct to be indexed just like arrays.
 🔑 Purpose: They enable array-like access to class data.
 🔑 Syntax: Uses the this keyword.
`
Types of Indexers
1. Single-Dimensional Indexer: Accesses elements using a single index.
2. Multi-Dimensional Indexer: Accesses elements using multiple indices (less common).

Example Code:

class SampleCollection {

private int[] arr = new int[10];

public int this[int index] {


get { return arr[index]; }
set { arr[index] = value; }
}
}

class Program {
static void Main() {
SampleCollection collection = new SampleCollection();
collection[0] = 10;
collection[1] = 20;
Console.WriteLine(collection[0]); // Output: 10
Console.WriteLine(collection[1]); // Output: 20
}
}
Output:

10
20
b) Interface

 🔑 Definition: An interface defines a contract that implementing classes must follow.


 🔑 Purpose: It allows different classes to be treated uniformly based on shared behavior.
 🔑 Syntax: Uses the interface keyword.

Types of Interfaces

1. Standard Interface: Contains method declarations without implementations.


2. Marker Interface: An empty interface that provides metadata (e.g., ICloneable).
3. Functional Interface: Contains a single abstract method (used in delegates).
4. Generic Interface: Allows for type parameters (e.g., IEnumerable<T>).
5. Multiple Interfaces: A class can implement multiple interfaces.
Example Code:

interface IAnimal {
void Speak();
}

class Dog : IAnimal {


public void Speak() {
Console.WriteLine("Woof!");
}
}

class Program {
static void Main() {
IAnimal myDog = new Dog();
myDog.Speak(); // Output: Woof!
}
}
Output:

Woof!

10. Discuss in detail about oops concepts.

Object-Oriented Programming (OOP)

Definition: Object-Oriented Programming (OOP) is a programming paradigm that uses "objects"


to represent data and methods. It emphasizes concepts such as encapsulation, inheritance,
polymorphism, and abstraction to create modular and reusable code.

Core Concepts of OOP

1. Classes and Objects


2. Encapsulation
3. Inheritance
4. Polymorphism
5. Abstraction
1. Classes and Objects

 Class: A blueprint for creating objects (instances).


 Object: An instance of a class.

Syntax

class ClassName {
// Class members (fields, methods)
}

Example

using System;

class Car {
public string Model;
public int Year;

public void DisplayInfo() {


Console.WriteLine($"Model: {Model}, Year: {Year}");
}
}

class Program {
static void Main(string[] args) {
Car myCar = new Car();
myCar.Model = "Toyota";
myCar.Year = 2020;
myCar.DisplayInfo();
}
}

Output

Model: Toyota, Year: 2020

2. Encapsulation

Definition: Encapsulation is the bundling of data (attributes) and methods (functions) that
operate on the data into a single unit or class, restricting direct access to some components.
- Hiding internal implementation details.
- Access modifiers: public, private, protected.
Syntax
class ClassName {
private int _field;

public int Property {


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

Example

using System;

class BankAccount {
private decimal balance;

public void Deposit(decimal amount) {


if (amount > 0) {
balance += amount;
}
}

public decimal GetBalance() {


return balance;
}
}

class Program {
static void Main(string[] args) {
BankAccount account = new BankAccount();
account.Deposit(100);
Console.WriteLine($"Balance: {account.GetBalance()}");
}
}

Output

Balance: 100
3. Inheritance

Definition: Inheritance allows a class to inherit members (fields and methods) from another
class.

Syntax

class BaseClass {
// Base class members
}

class DerivedClass : BaseClass {


// Derived class members
}

Example

using System;

class Animal {
public void Eat() {
Console.WriteLine("Eating...");
}
}

class Dog : Animal {


public void Bark() {
Console.WriteLine("Barking...");
}
}

class Program {
static void Main(string[] args) {
Dog myDog = new Dog();
myDog.Eat(); // Inherited method
myDog.Bark(); // Dog's own method
}
}

Output

Eating...
Barking...
4. Polymorphism

Definition: Polymorphism allows methods to do different things based on the object that it is
acting upon, typically achieved through method overriding and interfaces.

Syntax

class BaseClass {
public virtual void Display() {
Console.WriteLine("Base class display");
}
}

class DerivedClass : BaseClass {


public override void Display() {
Console.WriteLine("Derived class display");
}
}

Example

using System;

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

class Dog : Animal {


public override void Speak() {
Console.WriteLine("Dog barks");
}
}

class Program {
static void Main(string[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();

myAnimal.Speak(); // Calls Animal's Speak


myDog.Speak(); // Calls Dog's Speak
}
}
Output

Animal speaks
Dog barks

Polymorphism:
- Method Overloading: Multiple methods with same name but different parameters.
- Method Overriding: Derived class provides specific implementation.

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

public double Add(double a, double b)


{
return a + b;
}
}

// Method Overriding
public class Animal
{
public virtual void Sound()
{
Console.WriteLine("Generic sound");
}
}

public class Dog : Animal


{
public override void Sound()
{
Console.WriteLine("Barking");
}
}
5. Abstraction

Definition: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of the object.

Syntax

abstract class AbstractClass {


public abstract void AbstractMethod();
}

class ConcreteClass : AbstractClass {


public override void AbstractMethod() {
Console.WriteLine("Implemented abstract method");
}
}

Example

using System;

abstract class Shape {


public abstract double Area();
}

class Rectangle : Shape {


public double Width { get; set; }
public double Height { get; set; }

public override double Area() {


return Width * Height;
}
}

class Program {
static void Main(string[] args) {
Rectangle rect = new Rectangle();
rect.Width = 5;
rect.Height = 10;
Console.WriteLine($"Area of Rectangle: {rect.Area()}");
}
}
Output

Area of Rectangle: 50
Abstraction

- Showing only necessary information.


- Abstract classes and interfaces.

public abstract class Shape


{
public abstract double Area();
}

public class Circle : Shape


{
public double Radius { get; set; }

public override double Area()


{
return Math.PI * Radius * Radius;
}
}

11. Discuss inheritance in c#. Explain its types with suitable program.

What is Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a class (called a derived class) to inherit properties and methods from
another class (called a base class).
The following are the types of inheritance in C#.
The inheritance concept is based on a base class and its derived classes. Let us see
the definition of base and derived classes.
 Base class - the class from which features are to be inherited into another
class.
 Derived class - the class that is inherited from the base class.
Single inheritance in C#
A class inherits from one base class.
It is the type of inheritance in which there is one base class and one derived class.

Syntax:
class BaseClass {
// Base class members
}
class DerivedClass : BaseClass {
// Derived class members
}
EXAMPLE PROGRAM
using System;

public class Animal


{
public void Eat()
{
Console.WriteLine("Eating...");
}
}

public class Dog : Animal


{
public void Bark()
{
Console.WriteLine("Barking...");
}
}

class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Eating...
dog.Bark(); // Output: Barking...
}
}
Output
Eating...
Barking...
Multilevel inheritance
A subclass inherits from a superclass that itself inherits from another
superclass.
A class inherits from another derived class, forming a chain of
inheritance. This allows developers to create new classes based on existing
classes in a hierarchy.
Syntax:
class BaseClass {
// Base class members
}

class IntermediateClass : BaseClass {


// Intermediate class members
}

class DerivedClass : IntermediateClass {


// Derived class members
}
EXAMPLE PROGRAM
using System;

public class Animal


{
public void Eat()
{
Console.WriteLine("Eating...");
}
}

public class Dog : Animal


{
public void Bark()
{
Console.WriteLine("Barking...");
}
}

public class Puppy : Dog


{
public void Play()
{
Console.WriteLine("Playing...");
}
}

class Program
{
static void Main()
{
Puppy puppy = new Puppy();
puppy.Eat(); // Output: Eating...
puppy.Bark(); // Output: Barking...
puppy.Play(); // Output: Playing...
}
}
Output
Eating...
Barking...
Playing...
Hierarchical inheritance
Multiple subclasses inherit from a single superclass.
Multiple classes inherit from a single base class, creating a hierarchy.
This is useful when the features of the base class are required in multiple
classes.
Syntax:
class BaseClass {
// Base class members
}

class DerivedClass1 : BaseClass {


// Derived class 1 members
}

class DerivedClass2 : BaseClass {


// Derived class 2 members
}
EXAMPLE PROGRAM
using system;
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
public class Cat : Animal
{
public void Meow()
{
Console.WriteLine("Meowing...");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Eating...
dog.Bark(); // Output: Barking...
Cat cat = new Cat();
cat.Eat(); // Output: Eating...
cat.Meow(); // Output: Meowing...
}
}
Output
Eating...
Barking...
Eating...
Meowing...
Hybrid inheritance
Combination of multiple and multilevel inheritance.
A combination of multiple and multilevel inheritance. This allows a class to
inherit properties and behaviours from multiple base classes and create a
hierarchy of derived classes.

Syntax:
class BaseClass {
// Base class members
}
class DerivedClass1 : BaseClass {
// Derived class 1 members
}
class DerivedClass2 {
// Derived class 2 members
}
class FinalDerivedClass : DerivedClass1, IDog {
// Final derived class members
}
EXAMPLE PROGRAM

using System;

public class Animal


{
public void Eat()
{
Console.WriteLine("Eating...");
}
}

public class Mammal : Animal


{
public void Walk()
{
Console.WriteLine("Walking...");
}
}

public class Dog : Mammal


{
public void Bark()
{
Console.WriteLine("Barking...");
}
}

public class Cat : Mammal


{
public void Meow()
{
Console.WriteLine("Meowing...");
}
}

class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Eating...
dog.Walk(); // Output: Walking...
dog.Bark(); // Output: Barking...

Cat cat = new Cat();


cat.Eat(); // Output: Eating...
cat.Walk(); // Output: Walking...
cat.Meow(); // Output: Meowing...
}
}
Output

Eating...
Walking...
Barking...
Eating...
Walking...
Meowing...
12. How to create windows forms? Discuss various form events and controls with
example.
Creating a Windows Form
1. Open Visual Studio and create a new project.
2. Select "Windows Forms App (.NET Framework)" under the "Visual C#" section.
3. Name your project and click "OK."
4. Design your form by dragging and dropping controls from the Toolbox.

Form Events
1. Load: Occurs when the form is loaded.
2. Shown: Occurs when the form is shown.
3. Closing: Occurs when the form is closing.
4. Closed: Occurs when the form is closed.
5. Resize: Occurs when the form is resized.

Form Controls
1. Label: Displays text.
2. TextBox: Allows user input.
3. Button: Performs an action when clicked.
4. CheckBox: Allows user to select an option.
5. RadioButton: Allows user to select one option from multiple options.

Creating Windows Forms in C# involves using the .NET Framework to design graphical user
interfaces (GUIs) for desktop applications. Below is a guide on how to create Windows Forms,
along with a discussion of various form events and controls, including examples.

Creating Windows Forms

Step 1: Setting Up the Environment

1. Install Visual Studio: Download and install Visual Studio (Community Edition is free).
2. Create a New Project:
 Open Visual Studio.
 Select Create a new project.
 Choose Windows Forms App (.NET Framework).
 Click Next and configure your project settings.

Step 2: Designing the Form

1. Add Controls: Drag and drop controls from the Toolbox onto the form. Common controls
include:
 Button
 TextBox
 Label
 ComboBox
 ListBox
 CheckBox
 RadioButton
2. Set Properties: Select a control and use the Properties window to set its properties (e.g., Text,
Name, Size, Location).

Step 3: Writing Event Handlers

Events occur when users interact with controls. You can handle these events to execute code.

Example: Handling Button Click Event

1. Double-click the Button: This creates an event handler in the code-behind file.
2. Write Code:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
}

Example Code

Here’s a simple example that creates a form with a button and a label:

using System;

using System.Windows.Forms;

namespace MyWindowsFormsApp
{
public class MainForm : Form
{
private Button myButton;
private Label myLabel;

public MainForm()
{
myButton = new Button();
myButton.Text = "Click Me";
myButton.Location = new System.Drawing.Point(100, 100);
myButton.Click += new EventHandler(myButton_Click);

myLabel = new Label();


myLabel.Location = new System.Drawing.Point(100, 150);
myLabel.AutoSize = true;

Controls.Add(myButton);
Controls.Add(myLabel);
}

private void myButton_Click(object sender, EventArgs e)


{
myLabel.Text = "Button was clicked!";
}

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
Common Form Events

1. Load: Occurs when the form is loaded.


private void MainForm_Load(object sender, EventArgs e)
{
// Initialization code here
}

2. Click: Occurs when the form is clicked.


private void MainForm_Click(object sender, EventArgs e)
{
// Handle click event
}

3. Closing: Occurs when the form is about to close.


private void MainForm_Closing(object sender, FormClosingEventArgs e)
{
// Confirm before closing
}

4. Resize: Occurs when the form is resized.


private void MainForm_Resize(object sender, EventArgs e)
{
// Handle resizing
}

Example of Using Multiple Controls

private void InitializeComponent()


{
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.radioButton1 = new System.Windows.Forms.RadioButton();
// Additional initialization code...
}

13. Define MDI forms. Explain how to create MDI form with an example.
What are MDI Forms?

MDI (Multiple Document Interface) forms allow you to create an application where multiple
child windows are contained within a single parent window.

Examples include text editors like Microsoft Word, where multiple documents can be opened
inside one application window.

Definition of MDI Forms

MDI (Multiple Document Interface) forms are a type of Windows Forms application that allows
multiple child forms to be displayed within a single parent form.

The parent form is called the MDI parent, and the child forms are called MDI children.

MDI Forms

 MDI: Multiple Document Interface


 Purpose: Allows multiple child forms within a single parent form.
 Usage: Common in applications like text editors, IDEs.
Characteristics of MDI Forms

1. Single Parent Form: MDI forms have a single parent form that contains multiple child forms.
2. Multiple Child Forms: MDI forms can have multiple child forms that can be displayed within
the parent form.
3. Child Forms are Contained within the Parent Form: Child forms are displayed within the
boundaries of the parent form.
4. Child Forms can be Moved and Resized: Child forms can be moved and resized within the
parent form.

Creating MDI Forms in C#

1. Set Parent Form:


 Set IsMdiContainer to true.

2. Create Child Form:


 Instantiate a child form.
 Set MdiParent property.

3. Show Child Form:


 Call Show() method.

Example Code

// Parent Form (Form1)


public Form1()
{
InitializeComponent();
this.IsMdiContainer = true; // Enable MDI
}

// Child Form (Form2)


private void OpenChildForm()
{
Form2 child = new Form2(); // Create child form
child.MdiParent = this; // Set parent
child.Show(); // Display child form
}
Working with MDI Forms:

Here are some key things to note when working with MDI forms:
- Use the IsMdiContainer property to set the MDI parent form.
- Use the MdiParent property to set the parent form of the child form.
- Use the Show() method to display the MDI child form.
- Use the Close() method to close the MDI child form.
- Use the LayoutMdi() method to arrange the MDI child forms within the parent
form.
14. Illustrate standard controls and components of windows forms in .NET.
Standard Controls:
1. Label: Displays text or images.
2. Text Box: Allows users to enter text.
3. Button: Performs an action when clicked.
4. Check Box: Allows users to select an option.
5. Radio Button: Allows users to select one option from multiple options.
6. Combo Box: Displays a list of items and allows users to select one.
7. List Box: Displays a list of items and allows users to select one or multiple
items.
8. Data Grid View: Displays data in a grid format.
9. Picture Box: Displays images.
10. Progress Bar: Displays the progress of a task.

Containers:
1. Panel: A container control that can hold other controls.
2. Group Box: A container control that can hold other controls and has a caption.
3. Tab Control: A container control that can hold multiple pages of controls.
4. Split Container: A container control that can hold two panels that can be
resized.

Menus and Toolbars:


1. Menu Strip: A menu system that can be attached to a form.
2. Tool Strip: A toolbar that can hold buttons, dropdowns, and other controls.
3. Status Bar: A control that displays status information at the bottom of a form.
Dialogs:
1. Message Box: A dialog that displays a message to the user.
2. Open File Dialog: A dialog that allows users to select a file to open.
3. Save File Dialog: A dialog that allows users to select a file to save.
4. Font Dialog: A dialog that allows users to select a font.
5. Color Dialog: A dialog that allows users to select a color.

Here are the components of Windows Forms in .NET:


1. Forms: The top-level container for a Windows Forms application.
2. Controls: Reusable components that provide specific functionality, such as
buttons, text boxes, and labels.
3. Containers: Controls that can hold other controls, such as panels, group boxes,
and tab controls.
4. Menus: Collections of commands that can be invoked by the user, such as
menu strips and tool strips.
5. Dialogs: Forms that provide a specific function, such as open file dialogs, save
file dialogs, and message boxes.
6. Components: Non-visual components that provide specific functionality, such
as timers, error providers, and help providers.

Visual Components:
1. Buttons: Standard buttons, radio buttons, and check boxes.
2. Text Boxes: Single-line and multi-line text boxes.
3. Labels: Text labels that can be used to display text or images.
4. List Boxes: Controls that display a list of items.
5. Combo Boxes: Controls that display a list of items and allow the user to select
one.
6. Data Grid Views: Controls that display data in a grid format.
7. Picture Boxes: Controls that display images.

Non-Visual Components:
1. Timers: Components that raise an event at regular intervals.
2. Error Providers: Components that display error messages for other controls.
3. Help Providers: Components that provide help for other controls.
4. Data Sources: Components that provide data to other controls.

Standard Controls and Components of Windows Forms in .NET

Windows Forms provides a variety of standard controls and components to create rich desktop
applications. Here’s an overview of some of the most commonly used controls:

1. Label

 Description: Displays static text.


 Usage: Used for displaying information or prompts.
Label label = new Label();
label.Text = "Enter your name:";

2. TextBox

 Description: Allows users to input text.


 Usage: For single-line or multi-line text input.
TextBox textBox = new TextBox();
textBox.Multiline = true; // For multi-line input

3. Button

 Description: A clickable button.


 Usage: To trigger actions/events.
Button button = new Button();
button.Text = "Submit";
button.Click += (sender, e) => { /* Action */ };

4. CheckBox

 Description: A box that can be checked or unchecked.


 Usage: For binary choices.
CheckBox checkBox = new CheckBox();
checkBox.Text = "Agree to terms";

5. RadioButton

 Description: Allows selection of one option from a group.


 Usage: For mutually exclusive choices.
RadioButton radioButton = new RadioButton();
radioButton.Text = "Option 1";

6. ComboBox

 Description: A dropdown list for selection.


 Usage: To provide a list of options.
ComboBox comboBox = new ComboBox();
comboBox.Items.Add("Option 1");
comboBox.Items.Add("Option 2");

7. ListBox

 Description: Displays a list of items.


 Usage: For selecting one or more items.
ListBox listBox = new ListBox();
listBox.Items.Add("Item 1");

8. PictureBox

 Description: Displays images.


 Usage: To show graphics or icons.
PictureBox pictureBox = new PictureBox();
pictureBox.Image = Image.FromFile("path_to_image.jpg");

9. ProgressBar

 Description: Indicates the progress of an operation.


 Usage: For displaying progress in tasks.
ProgressBar progressBar = new ProgressBar();
progressBar.Value = 50; // Set progress percentage

10. MenuStrip

 Description: A menu at the top of the form.


 Usage: For application menus.
MenuStrip menuStrip = new MenuStrip();
ToolStripMenuItem fileMenu = new ToolStripMenuItem("File");
menuStrip.Items.Add(fileMenu);
11. StatusStrip

 Description: Displays status information at the bottom of the form.


 Usage: For showing messages or statuses.
StatusStrip statusStrip = new StatusStrip();
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel("Ready");
statusStrip.Items.Add(statusLabel);

12. ToolTip

 Description: Provides pop-up hints for controls.


 Usage: To give additional information about controls.
ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(button, "Click to submit");

15. Elucidate the Architecture of ADO.Net.

Architecture of ADO.NET

ADO.NET is a set of classes that expose data access services for .NET Framework programmers.
It provides a bridge between the front-end applications and the data sources, allowing
developers to interact with databases in a consistent manner.
Key Components of ADO.NET Architecture

1. Data Providers
 Definition: A data provider is a set of classes that are used to connect to a database, retrieve
data, and update the database.
 Types:
 SQL Server Data Provider: System.Data.SqlClient
 OLE DB Data Provider: System.Data.OleDb
 ODBC Data Provider: System.Data.Odbc
 Oracle Data Provider: System.Data.OracleClient (deprecated)

2. Data Set
 Definition: A disconnected, in-memory representation of data that can contain multiple tables
and relationships.
 Features:
 Supports multiple tables and relationships.
 Can be used to manage data in a disconnected manner.
 Provides methods for data manipulation and synchronization with the database.

3. Data Table
 Definition: Represents a single table of in-memory data.
 Features:
 Can contain rows and columns.
 Supports data operations like sorting, filtering, and searching.

4. Data Adapter
 Definition: Acts as a bridge between a Data Set and the data source for retrieving and saving
data.
 Features:
 Fills a Data Set with data from the database.
 Updates the database with changes made to the Data Set.

5. Connection
 Definition: Represents a connection to a specific data source.
 Usage: Used to establish a connection to the database.
 Example:
SqlConnection connection = new SqlConnection(connectionString);
6. Command
 Definition: Represents a SQL statement or stored procedure to execute against a data source.
 Usage: Used to perform operations like SELECT, INSERT, UPDATE, and DELETE.
 Example:
SqlCommand command = new SqlCommand("SELECT * FROM Users", connection);

7. Data Reader
 Definition: Provides a way to read a forward-only stream of rows from a data source.
 Features:
 Lightweight and efficient for reading data.
 Requires an open connection and is connected to the data source.
16. Briefly discuss about dataset with suitable program.

What is a Data Set?


A Data Set is a disconnected, in-memory representation of data that can be used to store and
manipulate data.
Example Program:
Here's a simple program that demonstrates how to create and manipulate a

Code:

using System;
using System.Data;

class DataSetExample
{
static void Main()
{
// Create a new DataSet
DataSet dataSet = new DataSet("MyDataSet");

// Create a new DataTable


DataTable dataTable = new DataTable("Customers");

// Add columns to the DataTable


dataTable.Columns.Add("CustomerID", typeof(int));
dataTable.Columns.Add("Name", typeof(string));

// Add rows to the DataTable


dataTable.Rows.Add(1, "John Doe");
dataTable.Rows.Add(2, "Jane Doe");

// Add the DataTable to the DataSet


dataSet.Tables.Add(dataTable);

// Display the data in the DataSet


Console.WriteLine("Customer Data:");
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine($"CustomerID: {row["CustomerID"]}, Name:
{row["Name"]}");
}
}
}

Output
Customer Data:
CustomerID: 1, Name: John Doe
CustomerID: 2, Name: Jane Doe
Key Features of Data Set:
- Disconnected architecture
- In-memory data storage
- Collection of Data Tables
- Data Relations for navigating related data
Types of Datasets

1. Structured Datasets
 Organized in a fixed format (e.g., tables).
 Example: SQL databases, Excel sheets.
2. Unstructured Datasets
 No predefined structure or format.
 Example: Text files, images, videos.
3. Semi-Structured Datasets
 Contains elements of both structured and unstructured data.
 Example: JSON, XML files.

You might also like