C Sharp
C Sharp
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.
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.
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() { ... }
}
General Properties
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.
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.
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
1. Definition
Serialization Process
1. Serialization
2. Deserialization
Serialization Types
Definition of a Transaction in C#
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.
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
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)
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 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
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 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:
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
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
(+).
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
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
(==).
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
Logical operators are used to perform logical operations in C#. They include && (logical AND),
|| (logical OR), and ! (logical NOT).
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 (&&).
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
Bitwise operators are used to perform operations at the bit level in C#.
Bitwise operators are particularly useful in scenarios where we need to work with binary data
or perform low-level operations.
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
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.
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:
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.
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
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.
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.
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.
Steps:
class Program
{
// Create a method
void SayHello()
{
Console.WriteLine("Hello from the method!");
}
1. Static Method
Example Program:
csharp
using System;
class Program
{
static void Greet()
{
Console.WriteLine("Hello from the static method!");
}
Output:
2. Instance Method
Example Program:
csharp
using System;
class Program
{
void ShowMessage()
{
Console.WriteLine("This is an instance method.");
}
Output:
3. Void Method
Example Program:
csharp
using System;
class Program
{
void PrintMessage()
{
Console.WriteLine("This is a void method, it doesn't
return anything.");
}
4. Return-Type Method
Example Program:
csharp
using System;
class Program
{
int AddNumbers(int a, int b)
{
return a + b; // Return the sum
}
Output:
Sum: 12
5. Parameterized Method
Example Program:
csharp
using System;
class Program
{
void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
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.");
}
Summary Table
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 {}.
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.
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
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
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
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. Null Reference Exception: Occurs when trying to access a member of a null
object .
System. IO Exception: Base class for input/output exceptions like file not found.
(File.ReadAllText("nonexistent.txt");).
(int.Parse("abc");).
System. Index Out Of Range Exception: Thrown when an array index is out of bounds.
System. Format Exception: Thrown when a string cannot be parsed to the desired type.
(int.Parse("12.3");).
using System;
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
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.
IndexOutOfRangeException This will occur when we try to access an element of an array or collection
with an index outside of its bounds.
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.
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
Example Program:
class Program
{
static void Main()
{
Student student = new Student();
Console.WriteLine(student.Name); // Output: Unknown
}
}
Output:
Unknown
2. Parameterized Constructor
Example Program:
public class Student
{
public string Name { get; set; }
class Program
{
static void Main()
{
Student student = new Student("John Doe");
Console.WriteLine(student.Name); // Output: John Doe
}
}
Output:
John Doe
3. Copy Constructor
Example Program:
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:
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;
class Program
{
static void Main()
{
Singleton obj = Singleton.GetInstance();
Console.WriteLine("Singleton instance created.");
}
}
Outputs:
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 {
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
Types of Interfaces
interface IAnimal {
void Speak();
}
class Program {
static void Main() {
IAnimal myDog = new Dog();
myDog.Speak(); // Output: Woof!
}
}
Output:
Woof!
Syntax
class ClassName {
// Class members (fields, methods)
}
Example
using System;
class Car {
public string Model;
public int Year;
class Program {
static void Main(string[] args) {
Car myCar = new Car();
myCar.Model = "Toyota";
myCar.Year = 2020;
myCar.DisplayInfo();
}
}
Output
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;
Example
using System;
class BankAccount {
private decimal 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
}
Example
using System;
class Animal {
public void Eat() {
Console.WriteLine("Eating...");
}
}
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");
}
}
Example
using System;
class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Program {
static void Main(string[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
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;
}
// Method Overriding
public class Animal
{
public virtual void Sound()
{
Console.WriteLine("Generic sound");
}
}
Definition: Abstraction is the concept of hiding the complex implementation details and
showing only the essential features of the object.
Syntax
Example
using System;
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
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;
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 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
}
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;
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Eat(); // Output: Eating...
dog.Walk(); // Output: Walking...
dog.Bark(); // Output: Barking...
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.
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.
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).
Events occur when users interact with controls. You can handle these events to execute code.
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);
Controls.Add(myButton);
Controls.Add(myLabel);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
Common Form Events
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.
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
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.
Example Code
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.
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.
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
2. TextBox
3. Button
4. CheckBox
5. RadioButton
6. ComboBox
7. ListBox
8. PictureBox
9. ProgressBar
10. MenuStrip
12. ToolTip
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.
Code:
using System;
using System.Data;
class DataSetExample
{
static void Main()
{
// Create a new DataSet
DataSet dataSet = new DataSet("MyDataSet");
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.