Describe the .Net program execution model in details.
1. Source Code: The process begins with the developer writing source code in a
.NET-supported language such as C#, VB.NET, or F#. This source code contains
the instructions and logic that define the behavior of the application.
2. Compilation: The source code is then compiled into an intermediate language
(IL) known as Common Intermediate Language (CIL) or Microsoft Intermediate
Language (MSIL). This compilation is performed by the .NET compiler (for
example, csc.exe for C# or vbc.exe for VB.NET). The output of this step is an
assembly containing metadata and CIL code.
3. Assembly: The compiled code is packaged into assemblies, which are self-
describing units of deployment in .NET. Assemblies can be either executable
(with an entry point) or libraries (containing reusable code). Assemblies also
contain metadata that describes types, members, and references to other
assemblies.
4. Loading: When the .NET application starts, the Common Language Runtime
(CLR) loads the required assemblies into memory. This loading process includes
locating the assemblies, verifying their integrity, and resolving dependencies.
5. Just-In-Time (JIT) Compilation: Once the assemblies are loaded, the CLR
performs JIT compilation, which translates the IL code into native machine
code specific to the underlying hardware architecture. This process happens
on-demand, just before the IL code is executed, and improves performance by
adapting the code to the execution environment.
6. Execution: With the code compiled to native machine code, the CLR begins
executing the application. It manages memory, handles exceptions, enforces
security, and provides various services such as garbage collection and
threading. The execution continues until the application terminates or
encounters an error.
7. Garbage Collection: As the application runs, the CLR periodically performs
garbage collection to reclaim memory occupied by objects that are no longer in
use. This automatic memory management helps prevent memory leaks and
improves the overall stability and performance of .NET applications.
8. Interoperability: .NET applications can interact with native code written in
languages like C and C++ through Platform Invocation Services (PInvoke) or by
using interoperability features like COM Interop. This allows .NET applications
to leverage existing libraries and APIs.
9. Security: The .NET runtime provides various security features such as code
access security, role-based security, and cryptographic services to help protect
applications from unauthorized access and malicious code.
Describe the .Net framework in details with block diagram.
The .NET Framework is a software development framework developed by Microsoft. It
provides a comprehensive and consistent programming model for building applications,
ranging from desktop and web applications to mobile and cloud-based services. Here's a
detailed description along with a block diagram:
1. Common Language Runtime (CLR):
• Execution Engine: The CLR is the runtime environment for .NET applications. It
manages memory, handles exceptions, and provides various services required by the
applications.
• Just-In-Time (JIT) Compiler: It compiles Intermediate Language (IL) code into
native machine code, ensuring performance optimization.
• Garbage Collector (GC): Manages memory allocation and releases memory
occupied by objects that are no longer in use, enhancing memory management
efficiency.
2. Base Class Library (BCL):
• Core Functionality: A set of classes, interfaces, and value types that provide
essential functionality for .NET applications.
• Collections: Includes classes for various data structures like lists, dictionaries, queues,
etc.
• Input/Output (I/O): Classes for handling file operations, streams, and network
communication.
• Networking: Provides classes for network protocols like HTTP, TCP/IP, etc.
• Security: Includes classes for encryption, decryption, and access control.
3. Language Integrated Query (LINQ):
• Querying Data: Enables developers to query data from different data sources (like
databases, XML, collections) using a unified syntax.
• Type-Safe Queries: Queries are type-safe and evaluated at compile time, reducing
runtime errors.
4. ASP.NET:
• Web Development Framework: A framework for building dynamic web applications
and services.
• Web Forms: Provides a familiar event-driven programming model for building web
applications.
• MVC (Model-View-Controller): A pattern for separating concerns in web
applications, providing better maintainability and testability.
• Web API: Facilitates building RESTful APIs for web services.
5. Windows Forms / WPF (Windows Presentation Foundation):
• UI Development: Frameworks for building desktop applications with rich user
interfaces.
• Windows Forms: Traditional framework for building Windows desktop applications.
• WPF: Provides a more modern and flexible approach to UI development, with
support for vector graphics, animations, and data binding.
6. Entity Framework:
• Object-Relational Mapping (ORM): Simplifies database interaction by abstracting
the database schema into objects.
• LINQ Support: Allows querying databases using LINQ syntax.
• Code-First Approach: Enables developers to define database schema using code,
with automatic database generation.
7. ASP.NET Core (.NET Core):
• Cross-platform Development: A modular and cross-platform version of ASP.NET,
allowing development on Windows, macOS, and Linux.
• Performance: Optimized for high performance and scalability, suitable for modern
cloud-based applications.
• Dependency Injection: Built-in support for dependency injection, enhancing
modularity and testability.
Block Diagram:
What is jagged array? Explain with suitable Example.
A jagged array is an array whose elements are arrays themselves, and those internal arrays can be of
different sizes. In other words, it's an array of arrays where each inner array can have a different
length
Example
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
// Accessing elements
Console.WriteLine(jaggedArray[0][1]); // Output: 2
Console.WriteLine(jaggedArray[1][0]); // Output: 4
Console.WriteLine(jaggedArray[2][2]); // Output: 8
What is delegate? Explain its types with suitable Example.
a delegate is a type that represents references to methods with a particular parameter list and return
type. Essentially, it's a way to pass a method as a parameter to another method, similar to function
pointers in languages like C or C++. Delegates are especially prevalent in languages like C# and
Java.
1. Singlecast Delegates: These delegates can hold references to a single method at a time.
When you assign a method to a singlecast delegate, it replaces any previously assigned
method.
Example
using System;
// Define a delegate type
delegate void MyDelegate(string message);
class Program
{
static void Main()
{
// Create an instance of the delegate
MyDelegate delegateInstance = new MyDelegate(PrintMessage);
// Invoke the delegate
delegateInstance("Hello, world!");
}
// Method to be assigned to the delegate
static void PrintMessage(string message)
{
Console.WriteLine(message);
}
}
2. Multicast Delegates: These delegates can hold references to multiple methods. When
invoked, all the methods are called in the order they were added.
Example
using System;
// Define a delegate type
delegate void MyDelegate(string message);
class Program
{
static void Main()
{
// Create an instance of the delegate
MyDelegate delegateInstance = null;
// Add methods to the delegate
delegateInstance += PrintMessage1;
delegateInstance += PrintMessage2;
// Invoke the delegate
delegateInstance("Hello, world!");
}
// Methods to be assigned to the delegate
static void PrintMessage1(string message)
{
Console.WriteLine("Message from method 1: " + message);
}
static void PrintMessage2(string message)
{
Console.WriteLine("Message from method 2: " + message);
}
}
What do you mean by static class and static method? Explain with example.
1. Static Class:
• A static class is a class that cannot be instantiated (meaning you can't create objects
of that class), and it contains only static members (properties, methods, etc.).
• Typically, static classes are used to hold utility methods or constants that are not
associated with specific instances of objects but are rather related to the class itself.
• Static classes are often used when you have a collection of methods that are logically
related to each other, but you don't need to maintain state across different
invocations.
Example
public static class MathUtility
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Subtract(int a, int b)
{
return a - b;
}
}
2. Static Method:
• A static method is a method that belongs to the class rather than any specific
instance of the class.
• Static methods can be called directly on the class itself, without needing to create an
instance of the class.
• They cannot access non-static (instance) members of the class directly because they
don't have access to any specific instance's state.
Example
public class StringUtils {
public static boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
}
What do you mean by lambda expression? Explain different types of lambda
expression used in C# with example.
a lambda expression is an anonymous function that you can use to create delegates or expression
tree types. Lambda expressions are concise and convenient for defining inline functions, especially
when you need to pass a function as an argument to another function or when you need to define
simple functions without explicitly declaring a separate method
syntax
(parameters) => expression
There are mainly two types of lambda expressions in C#:
1. Expression Lambdas: These are used when the lambda expression is a single expression.
The syntax is as follows:
(parameter) => expression
Example:
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
2. Statement Lambdas: These are used when the lambda expression requires multiple
statements. The syntax is similar to traditional method bodies enclosed in curly braces {}.
(parameters) => { statements; }
Example
Action<string> printMessage = (name) =>
{
string message = $"Hello, {name}!";
Console.WriteLine(message);
};
printMessage("John"); // Output: Hello, John!
Write a C# program to illustrate the concept of parameter pass by value and pass
by reference.
using System;
class Program
{
static void Main(string[] args)
{
int value = 10;
Console.WriteLine("Initial value: " + value);
// Passing by value
PassByValue(value);
Console.WriteLine("After pass by value: " + value);
// Passing by reference
PassByReference(ref value);
Console.WriteLine("After pass by reference: " + value);
Console.ReadLine();
}
static void PassByValue(int val)
{
// Modifying the parameter value doesn't affect the original value
val = 20;
Console.WriteLine("Inside PassByValue: " + val);
}
static void PassByReference(ref int val)
{
// Modifying the parameter value changes the original value
val = 30;
Console.WriteLine("Inside PassByReference: " + val);
}
}
What is Generics? What are its advantages? Write C# program to explain the
Concept?
Generics in programming languages like C# provide a way to create classes, interfaces, and
methods with placeholder types. These placeholder types can be specified by the user of
the generic class or method at the time of instantiation or invocation. This allows for code
reuse and type safety, as it enables the creation of flexible and reusable components that
can work with any data type.
Advantages of Generics:
1. Code Reusability: Generics allow you to write code that can work with any data type,
reducing the need to duplicate code for different types.
2. Type Safety: Generics enable type checking at compile-time, ensuring that type errors are
caught early in the development process.
3. Performance: Generics can improve performance by avoiding boxing and unboxing
operations that occur when working with non-generic collections.
4. Flexibility: Generics provide flexibility by allowing algorithms and data structures to be
parameterized by type, making them suitable for a wide range of scenarios.
using System;
public class GenericList<T>
{
private T[] _items;
private int _count;
public GenericList(int capacity)
{
_items = new T[capacity];
_count = 0;
}
public void Add(T item)
{
if (_count < _items.Length)
{
_items[_count] = item;
_count++;
}
else
{
Console.WriteLine("List is full. Cannot add more items.");
}
}
public void Display()
{
for (int i = 0; i < _count; i++)
{
Console.WriteLine(_items[i]);
}
}
}
class Program
{
static void Main(string[] args)
{
// Creating a list of integers
GenericList<int> intList = new GenericList<int>(5);
intList.Add(1);
intList.Add(2);
intList.Add(3);
intList.Display();
// Creating a list of strings
GenericList<string> stringList = new GenericList<string>(5);
stringList.Add("Hello");
stringList.Add("World");
stringList.Display();
}
}
Why namespaces is needed in C#? Write a C# program to create user defined
namespace and then use it in another namespace.
Namespaces in C# are used to organize and control the scope of classes, interfaces, structs, enums,
and other types in a C# program. They help in avoiding naming conflicts between different
components of a program, especially when integrating multiple libraries or working in large projects
// Define a namespace called MyNamespace
namespace MyNamespace
{
// Define a class inside the namespace
public class MyClass
{
public void Print()
{
Console.WriteLine("Inside MyNamespace.MyClass");
}
}
}
// Define another namespace
namespace AnotherNamespace
{
// Importing MyNamespace so that its contents can be used in this namespace
using MyNamespace;
// Define a class inside the new namespace
public class AnotherClass
{
public void Print()
{
Console.WriteLine("Inside AnotherNamespace.AnotherClass");
// Creating an instance of MyClass from MyNamespace and using it
MyClass myClass = new MyClass();
myClass.Print();
}
}
}
// Main program
class Program
{
static void Main(string[] args)
{
// Creating an instance of AnotherClass and using it
AnotherNamespace.AnotherClass anotherClass = new
AnotherNamespace.AnotherClass();
anotherClass.Print();
}
}
Define Command line argument in C# program. Provide two types of command line
arguments with example.
command-line arguments are the parameters passed to the program when it is executed from the
command line or terminal. These arguments can be accessed within the program to alter its
behavior or provide input data. Command-line arguments are stored in the args parameter of the
Main method.
using System;
class Program
{
static void Main(string[] args)
{
// Check if any command-line arguments are provided
if (args.Length > 0)
{
Console.WriteLine("Command-line arguments provided:");
// Print each argument
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
else
{
Console.WriteLine("No command-line arguments provided.");
}
}
}
Types of Command-Line Arguments:
1. Flag Arguments: These are boolean switches that either enable or disable
certain features of the program. They are usually represented as - or --
followed by a keyword.
Example:
program.exe –verbose
2.Value Arguments: These are arguments that pass a value to the program. They are
typically represented as the argument name followed by the value.
Example:
program.exe --output-file output.txt
Write a C# program to display Employee records in descending order with respect
to employee name using LINQ.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Define the Employee class
class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
}
// Create a list of Employee records
List<Employee> employees = new List<Employee>
{
new Employee { EmployeeId = 1, Name = "John", Salary = 50000 },
new Employee { EmployeeId = 2, Name = "Alice", Salary = 60000 },
new Employee { EmployeeId = 3, Name = "Bob", Salary = 55000 },
new Employee { EmployeeId = 4, Name = "David", Salary = 52000 }
};
// Use LINQ to sort the Employee records in descending order by Name
var sortedEmployees = employees.OrderByDescending(emp => emp.Name);
// Display the sorted Employee records
Console.WriteLine("Employee Records (Descending Order by Name):");
foreach (var employee in sortedEmployees)
{
Console.WriteLine($"Employee ID: {employee.EmployeeId}, Name:
{employee.Name}, Salary: {employee.Salary}");
}
Console.ReadLine();
}
}
What do you mean C# is type safety programming language? Describe the .Net
program execution model in details.
C# is often referred to as a "type-safe" programming language because it enforces type
safety at compile time. This means that C# ensures that operations performed on variables
are valid for their data types. For instance, you can't assign a string value to an integer
variable without explicit conversion.
Now, let's delve into the .NET program execution model:
1. Compilation: C# code is compiled into an intermediate language (IL) known as Common
Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL). This IL is a
platform-independent code that can be executed by the .NET runtime.
2. Just-In-Time (JIT) Compilation: When a .NET program is executed, the IL code is passed
through the Just-In-Time (JIT) compiler. JIT compilation translates the IL code into native
machine code that the underlying hardware can understand. This compilation is done
dynamically during runtime, optimizing the code for the specific hardware and environment
where the program is running.
3. Execution by the Common Language Runtime (CLR): The Common Language Runtime
(CLR) is the heart of the .NET framework. It provides various services like memory
management, exception handling, and security. The CLR loads the compiled IL code,
manages its execution, and ensures type safety and other security measures. It also provides
automatic garbage collection to reclaim memory occupied by objects that are no longer in
use.
4. Managed Execution: .NET programs are managed by the CLR. This means that the CLR is
responsible for managing the program's execution, including memory allocation, thread
management, and security. Managed execution provides several benefits such as automatic
memory management (garbage collection), robust security features, and interoperability
between different .NET languages.
5. Metadata and Reflection: .NET assemblies contain metadata that describes the types,
members, and other information about the code. This metadata is used by the CLR for
various purposes, including type safety verification, late binding, and reflection. Reflection
allows .NET programs to inspect and manipulate their own structure and behavior at
runtime, enabling advanced features like dynamic loading of assemblies and runtime code
generation.
What do you mean by multiple inheritance? Write a C# program to implement
concept of multiple inheritance using interface.
Multiple inheritance is a feature in object-oriented programming languages where a class can inherit
properties and behavior from more than one parent class
C#program below
using System;
// Define interface A
interface IA
{
void MethodA();
}
// Define interface B
interface IB
{
void MethodB();
}
// Implementing class implementing both interfaces
class MyClass : IA, IB
{
public void MethodA()
{
Console.WriteLine("Method A implemented");
}
public void MethodB()
{
Console.WriteLine("Method B implemented");
}
}
class Program
{
static void Main(string[] args)
{
// Create an object of the implementing class
MyClass myClassObj = new MyClass();
// Call methods defined in interfaces
myClassObj.MethodA();
myClassObj.MethodB();
}
}
Write a C# program to show insert and select operation in database.
using System;
using System.Data.SqlClient;
class Program
{
// Connection string to the database
static string connectionString = "Data Source=YourServerName;Initial
Catalog=YourDatabaseName;Integrated Security=True";
static void Main(string[] args)
{
// Inserting data into the database
InsertData("John", 25);
// Selecting data from the database
SelectData();
}
static void InsertData(string name, int age)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO Persons (Name, Age) VALUES (@Name, @Age)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Age", age);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"{rowsAffected} row(s) inserted successfully.");
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
static void SelectData()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Persons";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"Name: {reader["Name"]}, Age:
{reader["Age"]}");
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Describe ADO.NET connected and Disconnected Architecture with diagram.
How virtual method is used to achieve dynamic binding in C#? Explain with the help
of suitable program.
ADO.NET Connected Architecture:
In ADO.NET connected architecture, the connection between the database and the
application remains open throughout the session. It involves the following steps:
1. Establish Connection: The application establishes a connection to the database using the
Connection object.
2. Execute Commands: The application executes SQL commands (such as SELECT, INSERT,
UPDATE, DELETE) directly on the connected database using Command objects.
3. Retrieve Data: The data retrieved from the database is stored in DataReader objects.
4. Process Data: The application processes the data directly from the DataReader.
Here's a basic diagram illustrating the connected architecture of ADO.NET:
Application <--> Connection <--> Command <--> DataReader <--> Database
ADO.NET Disconnected Architecture:
In ADO.NET disconnected architecture, the connection to the database is opened only when
necessary (during data retrieval or update) and is closed immediately after that. It involves
the following steps:
1. Establish Connection: The application establishes a connection to the database using the
Connection object.
2. Retrieve Data: The application fills a DataSet or DataTable with data from the database
using DataAdapter objects.
3. Close Connection: The connection to the database is closed.
4. Manipulate Data: The application manipulates the data in the DataSet or DataTable.
5. Update Database: Changes made to the DataSet or DataTable are updated back to the
database using DataAdapter objects.
Here's a basic diagram illustrating the disconnected architecture of ADO.NET:
Application <--> Connection <--> DataSet/DataTable <--> Database
Virtual program
using System;
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}
}
class Square : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a square");
}
}
class Program
{
static void Main(string[] args)
{
Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.Draw(); // Output: Drawing a circle
shape2.Draw(); // Output: Drawing a square
}
}
Write a C# program to create class complex having two private data number real
and imaginary suitable constructors and two methods addComplex() and
displayComplex(). Create another class text to create object of complex class and
use Its member.
using System;
// Complex class representing complex numbers
class Complex
{
private double real;
private double imaginary;
// Constructor to initialize real and imaginary parts
public Complex(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
// Method to add two complex numbers
public Complex AddComplex(Complex other)
{
double newReal = this.real + other.real;
double newImaginary = this.imaginary + other.imaginary;
return new Complex(newReal, newImaginary);
}
// Method to display complex number
public void DisplayComplex()
{
Console.WriteLine($"{real} + {imaginary}i");
}
}
// Test class to demonstrate the usage of Complex class
class Test
{
static void Main(string[] args)
{
// Create two complex numbers
Complex complex1 = new Complex(3, 2);
Complex complex2 = new Complex(5, -1);
// Add two complex numbers
Complex result = complex1.AddComplex(complex2);
// Display the result
Console.WriteLine("Sum of complex numbers:");
result.DisplayComplex();
}
}
What are the keywords used in exception handling? Write C# program that will
read name from keywords and display it on screen. The program should throw an
exception when length of name is more than 10 characters.
In C#, the keywords used in exception handling are try, catch, finally, throw, and finally
using System;
class Program
{
static void Main()
{
try
{
Console.Write("Enter your name: ");
string name = Console.ReadLine();
if (name.Length > 10)
{
throw new Exception("Name length should not exceed 10 characters.");
}
Console.WriteLine($"Your name is: {name}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Any cleanup code can be placed here
Console.WriteLine("Program execution completed.");
}
}
}
Write a C# program to connect to the database and insert 3 Customer records and
delete the customer record from Bank database whose Deposit amount is less than
500.(Database: Bank, Table: Customer(Account_no, Name, Address, Deposit_amount)).
using System;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Your_Connection_String_Here";
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection
connection.Open();
// Insert 3 Customer records
InsertCustomer(connection, 101, "John Doe", "123 Main St", 1000);
InsertCustomer(connection, 102, "Jane Smith", "456 Elm St", 200);
InsertCustomer(connection, 103, "Alice Johnson", "789 Oak St", 700);
// Delete records where Deposit amount is less than 500
DeleteCustomersWithLowDeposit(connection);
// Close the connection
connection.Close();
}
Console.WriteLine("Operation completed successfully.");
Console.ReadLine();
}
static void InsertCustomer(SqlConnection connection, int accountNo, string name, string address,
decimal depositAmount)
{
string query = "INSERT INTO Customer (Account_no, Name, Address, Deposit_amount) VALUES
(@AccountNo, @Name, @Address, @DepositAmount)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@AccountNo", accountNo);
command.Parameters.AddWithValue("@Name", name);
command.Parameters.AddWithValue("@Address", address);
command.Parameters.AddWithValue("@DepositAmount", depositAmount);
command.ExecuteNonQuery();
}
}
static void DeleteCustomersWithLowDeposit(SqlConnection connection)
{
string query = "DELETE FROM Customer WHERE Deposit_amount < 500";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
}
What do you mean by operator overloading? Write a C# program to create a class
Distance. The class should have two fields for feet and inch. It should have
constructor to initialize the feet and inch and method displayDistance() to print the
Distance. Overload the following operators:
- (Subtract two distance object)
- (Compare two Distance Object)
Operator overloading allows you to redefine the behavior of operators such as +, -, *, /, etc., for
user-defined types. In C#, you can overload operators to perform specific operations when they are
used with instances of your custom classes.
using System;
class Distance
{
private int feet;
private int inches;
public Distance(int feet, int inches)
{
this.feet = feet;
this.inches = inches;
}
public void DisplayDistance()
{
Console.WriteLine($"Distance: {feet} feet, {inches} inches");
}
// Overloading the - operator to subtract one Distance object from another
public static Distance operator -(Distance d1, Distance d2)
{
int totalInches1 = d1.feet * 12 + d1.inches;
int totalInches2 = d2.feet * 12 + d2.inches;
int differenceInches = totalInches1 - totalInches2;
int feet = differenceInches / 12;
int inches = differenceInches % 12;
return new Distance(feet, inches);
}
// Overloading the > operator to compare two Distance objects
public static bool operator >(Distance d1, Distance d2)
{
int totalInches1 = d1.feet * 12 + d1.inches;
int totalInches2 = d2.feet * 12 + d2.inches;
return totalInches1 > totalInches2;
}
// Overloading the < operator to compare two Distance objects
public static bool operator <(Distance d1, Distance d2)
{
return !(d1 > d2);
}
}
class Program
{
static void Main(string[] args)
{
Distance distance1 = new Distance(5, 9);
Distance distance2 = new Distance(3, 6);
// Display the distances
Console.WriteLine("Distance 1:");
distance1.DisplayDistance();
Console.WriteLine("\nDistance 2:");
distance2.DisplayDistance();
// Subtract distance2 from distance1
Distance difference = distance1 - distance2;
Console.WriteLine("\nDistance 1 - Distance 2:");
difference.DisplayDistance();
// Compare the distances
if (distance1 > distance2)
{
Console.WriteLine("\nDistance 1 is greater than Distance 2.");
}
else if (distance1 < distance2)
{
Console.WriteLine("\nDistance 1 is less than Distance 2.");
}
else
{
Console.WriteLine("\nDistance 1 is equal to Distance 2.");
}
}
}
Write a C# program to create a class time with three attributes hours, minutes and
second. Use appropriate constructor to initialize instance variables. Use method to
display time in HH:MM:SS format. Add and Subtract two times object. Implement
the class to add subtract and display time object
using System;
class Time
{
private int hours;
private int minutes;
private int seconds;
// Constructor
public Time(int hours, int minutes, int seconds)
{
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
// Method to display time in HH:MM:SS format
public void DisplayTime()
{
Console.WriteLine($"{hours:00}:{minutes:00}:{seconds:00}");
}
// Method to add two Time objects
public Time AddTime(Time otherTime)
{
int totalSeconds1 = hours * 3600 + minutes * 60 + seconds;
int totalSeconds2 = otherTime.hours * 3600 + otherTime.minutes * 60 +
otherTime.seconds;
int sumSeconds = totalSeconds1 + totalSeconds2;
int h = sumSeconds / 3600;
int m = (sumSeconds % 3600) / 60;
int s = sumSeconds % 60;
return new Time(h, m, s);
}
// Method to subtract two Time objects
public Time SubtractTime(Time otherTime)
{
int totalSeconds1 = hours * 3600 + minutes * 60 + seconds;
int totalSeconds2 = otherTime.hours * 3600 + otherTime.minutes * 60 +
otherTime.seconds;
int diffSeconds = totalSeconds1 - totalSeconds2;
int h = diffSeconds / 3600;
int m = (diffSeconds % 3600) / 60;
int s = diffSeconds % 60;
return new Time(h, m, s);
}
}
class Program
{
static void Main(string[] args)
{
// Creating Time objects
Time time1 = new Time(5, 30, 15);
Time time2 = new Time(2, 15, 45);
// Displaying times
Console.WriteLine("Time 1:");
time1.DisplayTime();
Console.WriteLine("Time 2:");
time2.DisplayTime();
// Adding times
Console.WriteLine("\nAdding times:");
Time sumTime = time1.AddTime(time2);
Console.WriteLine("Sum:");
sumTime.DisplayTime();
// Subtracting times
Console.WriteLine("\nSubtracting times:");
Time diffTime = time1.SubtractTime(time2);
Console.WriteLine("Difference:");
diffTime.DisplayTime();
}
}
Provided that a MySQL database named “University” with table named “Student”
with following columns (Rollnumber as int, Name as varchar(50), Department as
varchar(50), Address as varchar(50), Tution_fee as float). Write a C# program to
connect to database and insert 5 student records and display the student record
from University database who’s Department is “BCA” and delete others.
using System;
using MySql.Data.MySqlClient;
namespace UniversityDatabase
{
class Program
{
static void Main(string[] args)
{
string connectionString =
"Server=localhost;Database=University;Uid=root;Pwd=password;";
MySqlConnection connection = new MySqlConnection(connectionString);
try
{
connection.Open();
// Inserting 5 student records
InsertStudentRecords(connection);
// Displaying student records from the "BCA" department
DisplayStudentsInBCADepartment(connection);
// Deleting student records from departments other than "BCA"
DeleteStudentsNotInBCADepartment(connection);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
connection.Close();
}
}
static void InsertStudentRecords(MySqlConnection connection)
{
string query = "INSERT INTO Student (Rollnumber, Name, Department,
Address, Tution_fee) VALUES ";
string[] records = {
"(1, 'John Doe', 'BCA', '123 Main St', 1000.00)",
"(2, 'Jane Smith', 'BCA', '456 Elm St', 1200.00)",
"(3, 'Michael Johnson', 'BBA', '789 Oak St', 1100.00)",
"(4, 'Emily Wilson', 'MBA', '101 Pine St', 1300.00)",
"(5, 'David Brown', 'BCA', '222 Maple St', 1050.00)"
};
query += string.Join(",", records);
MySqlCommand command = new MySqlCommand(query, connection);
command.ExecuteNonQuery();
Console.WriteLine("Student records inserted successfully.");
}
static void DisplayStudentsInBCADepartment(MySqlConnection connection)
{
string query = "SELECT * FROM Student WHERE Department = 'BCA'";
MySqlCommand command = new MySqlCommand(query, connection);
MySqlDataReader reader = command.ExecuteReader();
Console.WriteLine("\nStudents in BCA Department:");
Console.WriteLine("Rollnumber\tName\t\tDepartment\tAddress\t\tTution_fee");
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)}\t\t{reader.GetString(1)}\t\t{reader.GetStri
ng(2)}\t\t{reader.GetString(3)}\t\t{reader.GetFloat(4)}");
}
reader.Close();
}
static void DeleteStudentsNotInBCADepartment(MySqlConnection connection)
{
string query = "DELETE FROM Student WHERE Department <> 'BCA'";
MySqlCommand command = new MySqlCommand(query, connection);
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine($"\n{rowsAffected} student records deleted.");
}
}
}
What is web server control in ASP.NET? List five web server control used in
ASP.NET. Write a program to create student registration form in one ASP.NET page
and display filled data with another page.
In ASP.NET, web server controls are elements that run on the server and generate HTML
that is sent to the client browser. These controls encapsulate common HTML functionality
and provide developers with a way to create rich, interactive web applications using server-
side code.
Here are five commonly used web server controls in ASP.NET:
1. TextBox: Allows users to input text.
2. Button: Triggers an action when clicked.
3. DropDownList: Presents a list of options for the user to choose from.
4. CheckBox: Enables users to select one or more options from a list.
5. GridView: Displays tabular data with built-in features like paging, sorting, and editing.
StudentRegistration.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="StudentRegistration.aspx.cs" Inherits="StudentRegistration" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Registration</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Student Registration Form</h2>
<div>
<asp:Label runat="server" Text="Name:"></asp:Label>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
</div>
<div>
<asp:Label runat="server" Text="Email:"></asp:Label>
<asp:TextBox runat="server" ID="txtEmail"></asp:TextBox>
</div>
<div>
<asp:Label runat="server" Text="Course:"></asp:Label>
<asp:DropDownList runat="server" ID="ddlCourse">
<asp:ListItem Text="Mathematics" Value="Math"></asp:ListItem>
<asp:ListItem Text="Physics" Value="Physics"></asp:ListItem>
<asp:ListItem Text="Chemistry" Value="Chemistry"></asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Button runat="server" ID="btnSubmit" Text="Submit"
OnClick="btnSubmit_Click" />
</div>
</div>
</form>
</body>
</html>
StudentRegistration.aspx.cs
using System;
using System.Web.UI;
public partial class StudentRegistration : Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Retrieve data from the form
string name = txtName.Text;
string email = txtEmail.Text;
string course = ddlCourse.SelectedValue;
// Store data in session for passing to another page
Session["Name"] = name;
Session["Email"] = email;
Session["Course"] = course;
// Redirect to another page to display the filled data
Response.Redirect("DisplayRegistration.aspx");
}
}
DisplayRegistration.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="DisplayRegistration.aspx.cs" Inherits="DisplayRegistration" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Display Registration</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Student Registration Details</h2>
<div>
<strong>Name:</strong> <%= Session["Name"] %>
</div>
<div>
<strong>Email:</strong> <%= Session["Email"] %>
</div>
<div>
<strong>Course:</strong> <%= Session["Course"] %>
</div>
</div>
</form>
</body>
</html>