100% found this document useful (1 vote)
1K views

Dot Net Framework

Uploaded by

omshewale20195
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Dot Net Framework

Uploaded by

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

Dot Net Framework

*Each Question 2 Marks


1. What is CTS?
Common Type System (CTS):
In the context of Microsoft's .NET framework, CTS refers to the Common
Type System. The Common Type System is a set of standards that
defines how types are declared, used, and managed in the Common
Language Runtime (CLR) of the .NET framework.
CTS ensures that types defined in different languages within the .NET
framework can interact seamlessly. It defines common data types, rules
for type conversion, and other guidelines to enable language
interoperability.

2. State any two advantages of .Net.


1)Language Independence:
One significant advantage of .NET is its support for multiple
programming languages. Developers can use languages such as C#,
VB.NET, F#, and more to build applications within the .NET framework.
The Common Language Runtime (CLR) ensures language interoperability,
allowing components written in different languages to seamlessly work
together. This flexibility is advantageous for development teams with
diverse skill sets.

2)Robust Security Model:


.NET incorporates a robust security model that helps developers build
secure applications. It includes features such as code access security,
role-based security, and cryptographic services.
Code access security ensures that only authorized code is allowed to
run, and role-based security allows developers to control access to
resources based on user roles. These security features contribute to the
development of more secure and reliable applications.

3. What is Event Driven Programming?


Event-driven programming is a paradigm in software development
where the flow of the program is determined by events such as user
actions, sensor outputs, or messages from other programs or threads. In
event-driven programming, the program structure is designed to
respond to events as they occur

4. Explain difference between menu and popup menu in .Net.


5. List any two properties of Radio Button Control.
1)GroupName Property:
The GroupName property is a key property of radio buttons that defines
the logical grouping of radio buttons. Radio buttons within the same
group share the same GroupName, which means that selecting one
radio button automatically deselects the others in the same group.
This property is crucial for ensuring that only one option within a group
can be selected at a time, as it establishes the mutual exclusivity of radio
buttons within the same group.

2) Checked Property:
The Checked property indicates whether a particular radio button is
selected or not. It is a boolean property, and when set to true, it means
the radio button is selected, and when set to false, it means the radio
button is not selected.
Typically, only one radio button in a group should have the Checked
property set to true at a time, as the purpose of radio buttons is to allow
a single selection from the group.

6. What do you mean by value type and Reference type?


1)Value Type:
Definition:
A value type is a data type where the variable directly contains its data.
The actual value is stored in the memory location assigned to the
variable.
Value types are typically simple types like integers, floating-point
numbers, characters, and structures.
2)Reference Type:
Definition:
A reference type is a data type where the variable stores a reference
(memory address) to the location where the actual data is stored.
Objects, arrays, classes, and interfaces are examples of reference types.

7. What is boxing in C#?


C#, boxing is the process of converting a value type to the corresponding
reference type (object type) by encapsulating the value in an object.
Essentially, it involves wrapping a value type within an object so that it
can be treated as an object.

8. What is mean by ADO.Net?


ADO.NET (ActiveX Data Objects for .NET) is a set of classes and libraries
provided by Microsoft as part of the .NET Framework for accessing and
manipulating data from various data sources. It is a data access
technology that enables communication between applications and
databases, allowing developers to interact with relational databases and
other data services.

9. Enlist any four data types used in .Net?


.NET, various data types are used to represent different kinds of values.
Here are four common data types used in .NET:
1)Integer Data Type (int):
Represents whole numbers without decimal points.
Example: int myNumber = 42;

2)String Data Type (string):


Represents sequences of characters (text).
Example: string myText = "Hello, World!";

3)Floating-Point Data Type (float and double):


float: Represents single-precision floating-point numbers.
Example: float myFloat = 3.14f;
double: Represents double-precision floating-point numbers.
Example: double myDouble = 3.14159265359;

4)Boolean Data Type (bool):


Represents a binary value indicating true or false.
Example: bool isTrue = true;

10.What is use of ‘this’ keyword in C#?


In C#, the this keyword is used to refer to the instance of the current
class. It is a reference to the current object on which the method,
property, or constructor is being invoked. The primary uses of the this
keyword include:

Distinguishing between Instance Variables and Local Variables:

When there is a naming conflict between an instance variable (a field or


property of the class) and a local variable (a variable declared within a
method), the this keyword helps to differentiate them.
*Each Question 4 Marks
1. Explain ASP .NET page life cycle in detail.
The ASP.NET page life cycle describes the sequence of events that occur
from the creation to the disposal of an ASP.NET web page.
Understanding the page life cycle is essential for developers to
effectively manage the state of controls, handle events, and perform
other tasks during the lifecycle stages. The ASP.NET page life cycle
consists of various stages, and each stage involves specific events. Here
is a detailed explanation of the ASP.NET page life cycle:
1)Page Request:
The page life cycle begins when a user requests an ASP.NET page by
navigating to a URL or clicking a link.
2)Start:
The Page object is created, and the Init event is triggered. Developers
can use the Init event to initialize the page and its controls.
During this stage, the page is initialized, and control properties are set.
3)Load View State:
If the page contains controls with EnableViewState set to true, the
ViewState data is loaded during the LoadViewState event.
ViewState is a mechanism to persist the state of controls across
postbacks.
4)Load Postback Data:
If the page is being processed in response to a postback (e.g., a button
click), the postback data is loaded during the LoadPostData event.
Controls that implement IPostBackDataHandler participate in this stage.

5)Load:
The Load event is triggered. Developers commonly use this event to
perform tasks such as populating controls, retrieving data, or handling
user input.
During this stage, data-bound controls are populated, and control
properties are set based on the ViewState and postback data.
6)Raise Postback Event:
If the page is being processed in response to a postback, the control that
caused the postback triggers its corresponding event during the
RaisePostBackEvent event.
For example, a button click triggers the Click event.
7)PreRender:
The PreRender event is triggered. Developers often use this event to
perform final changes to the page or its controls before rendering.
During this stage, changes made to controls are persisted, and the
ViewState is updated.
8)Save State (Save ViewState):
The SaveViewState event is triggered, allowing controls to save their
state information to the ViewState.
The state information includes properties that need to be persisted
across postbacks.
9)Save Postback Data:
If controls implement IPostBackDataHandler, the SavePostData event is
triggered to allow them to save their postback data.
This stage is crucial for maintaining state across postbacks.
10)Render:
The Render event is triggered, and the HTML markup for the page is
generated.
During this stage, the output for controls is rendered, and the resulting
HTML is sent to the browser.
11)Unload:
The Unload event is triggered. Developers can use this event for final
cleanup tasks before the page is unloaded from memory.
After the Unload event, the page is disposed of.

2. What are the classes in ADO.Net. Explain in detail.


ADO.NET (ActiveX Data Objects for .NET) provides a set of classes that
enable data access and manipulation in .NET applications. These classes
are part of the .NET Framework and facilitate interactions with
databases, XML files, and other data sources. The key classes in
ADO.NET include:
1)SqlConnection:
Represents a connection to a SQL Server database.
Provides methods for opening, closing, and managing the connection.
Example:
using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
// Perform database operations
}

2) SqlCommand:
Represents a SQL statement or stored procedure to execute against a
SQL Server database.
Used to execute queries, updates, inserts, and other SQL operations.
Example:
using (SqlCommand command = new SqlCommand("SELECT * FROM
Customers", connection))
{
SqlDataReader reader = command.ExecuteReader();
// Process the results
}

3) SqlDataAdapter:
Represents a set of data commands and a database connection for
populating a DataSet and updating the database.
Acts as a bridge between a DataSet and a database.
Example:
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Products", connection))
{
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Products");
// Work with the DataSet
}

4) DataSet:
Represents an in-memory cache of data retrieved from a data source.
Consists of one or more DataTable objects, each representing a table of
data.
Example:
DataSet dataSet = new DataSet();
dataSet.Tables.Add(new DataTable("Customers"));

5) DataTable:
Represents an in-memory table of data within a DataSet.
Contains rows and columns, much like a database table.
Example:
DataTable dataTable = new DataTable("Orders");
dataTable.Columns.Add("OrderID", typeof(int));
dataTable.Columns.Add("CustomerID", typeof(string));

6) DataReader:
Provides a forward-only, read-only stream of data from a data source.
Typically used for retrieving large result sets efficiently.
Example:
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Process each row
}
}

7) SqlParameter:
Represents a parameter to a SqlCommand and optionally its mapping to
DataSet columns.
Used to pass parameters to SQL queries or stored procedures.
Example:
SqlCommand command = new SqlCommand("INSERT INTO Employees
(FirstName, LastName) VALUES (@FirstName, @LastName)",
connection);
command.Parameters.Add(new SqlParameter("@FirstName", "John"));
command.Parameters.Add(new SqlParameter("@LastName", "Doe"));

8) SqlTransaction:
Represents a transaction to be made in the SQL Server database.
Provides methods for committing or rolling back a transaction.
Example:
using (SqlTransaction transaction = connection.BeginTransaction())
{
// Execute SQL commands within the transaction
transaction.Commit();
}

3. How to create menus in VB.Net?


In VB.NET, you can create menus using the MenuStrip control, which is a
container for menu items in Windows Forms applications. The
MenuStrip control provides a straightforward way to design and
organize menus and submenus in your application. Here are the steps to
create menus in VB.NET:
Create a new Windows Forms Application:
Open Visual Studio.
Create a new Windows Forms Application project.
Add a MenuStrip control to your form:
Open the form in the designer.
From the Toolbox, drag and drop a MenuStrip control onto your form.
Add Menu Items:
Click on the MenuStrip control to select it.
In the Properties window, find the Items property.
Click the ellipsis (...) button next to the Items property to open the
MenuStrip Items Collection Editor.
Use the editor to add ToolStripMenuItem controls, which represent
individual menu items.
You can organize items into drop-down menus by adding
ToolStripMenuItem controls as children of other ToolStripMenuItem
controls.
Set Properties for Menu Items:
Select each ToolStripMenuItem and set its Text property to specify the
text that will appear on the menu.
Set the Name property to provide a unique identifier for each menu
item.
You can also set other properties such as ShortcutKeys, ToolTipText, and
event handlers like Click for handling menu item clicks.
Handle Menu Item Click Events:
Double-click on a menu item to generate an event handler for the Click
event in the code-behind.
Implement the desired functionality inside the event handler method.

4. Enlist and explain various objectives of .Net frameworks.


The .NET framework is a comprehensive platform developed by
Microsoft for building, deploying, and running various types of
applications. It encompasses a set of technologies, tools, and libraries
that facilitate the development of robust and scalable software
solutions. The objectives of the .NET framework are broad, aiming to
address various aspects of application development. Here are several
key objectives of the .NET framework:
1)Language Independence:
Objective: To support multiple programming languages and enable
developers to choose the language that best suits their requirements
and expertise.
Explanation: The Common Language Runtime (CLR) within the .NET
framework allows different languages (such as C#, VB.NET, F#, and
more) to interoperate seamlessly. This language independence enhances
flexibility and facilitates collaboration among developers using different
languages.
2)Platform Independence:
Objective: To enable application development that is not tied to a
specific operating system, promoting cross-platform compatibility.
Explanation: .NET Core and later versions of the .NET framework are
designed to be cross-platform, allowing developers to build and run
applications on Windows, macOS, and Linux. This helps in reaching a
broader audience and simplifies deployment.
Simplified Development and Deployment:

Objective: To streamline the development process and simplify


deployment of applications.
Explanation: Features such as Just-In-Time (JIT) compilation, automatic
memory management (garbage collection), and a consistent runtime
environment contribute to easier development. Additionally,
deployment mechanisms like ClickOnce and containerization further
simplify the distribution and installation of applications.
Interoperability:

Objective: To facilitate interoperability between different technologies


and systems.
Explanation: .NET supports interoperability with COM (Component
Object Model) components, and technologies like P/Invoke enable
interaction with native code. This ensures that .NET applications can
seamlessly integrate with existing systems and components.
Security:

Objective: To provide a secure runtime environment and tools for


developing secure applications.
Explanation: The .NET framework includes features such as Code Access
Security (CAS), role-based security, and cryptography services. These
features help developers implement security measures and protect
applications from unauthorized access and malicious activities.
Scalability and Performance:

Objective: To support the development of scalable and high-


performance applications.
Explanation: The runtime optimizations, Just-In-Time compilation, and
performance monitoring tools contribute to creating applications that
can scale to handle increased workloads efficiently.
Unified Class Library:
Objective: To provide a comprehensive and consistent set of class
libraries that can be used across different types of applications.
Explanation: The .NET framework includes a vast and standardized class
library known as the Base Class Library (BCL). This library contains
reusable components for tasks such as file I/O, networking,
cryptography, and more, making it easier for developers to build
applications.
Web Services and XML Integration:

Objective: To enable the development of web services and facilitate


integration with XML-based technologies.
Explanation: The .NET framework includes support for creating and
consuming web services through technologies like ASP.NET Web
Services (ASMX) and Windows Communication Foundation (WCF).
Additionally, XML is integrated into the framework, providing tools for
XML parsing, transformation, and serialization.
Rich Development Environment:

Objective: To offer a rich and integrated development environment with


powerful tools and IDE support.
Explanation: Visual Studio, Microsoft's integrated development
environment (IDE) for .NET, provides a feature-rich environment with
code editing, debugging, profiling, and testing tools. It enhances
developer productivity and supports various application types, including
web, desktop, mobile, and cloud-based applications.

5. State and explain various statements used in VB.Net.


Visual Basic .NET (VB.NET), statements are instructions that perform
specific actions. Here are some common types of statements used in
VB.NET along with explanations:
1)Assignment Statements:
Syntax: variable = expression
Explanation: Assigns the value of the expression to the variable. For
example:
Dim age As Integer
age = 25
2)If Statements:

Syntax:
If condition Then
' Code to execute if the condition is true
Else
' Code to execute if the condition is false

3)End If
Explanation: Executes specific code blocks based on a given condition.
Select Case Statements:
Syntax:
Select Case expression
Case value1
' Code to execute for value1
Case value2
' Code to execute for value2
Case Else
' Code to execute if no match is found
4)End Select
Explanation: Provides a way to execute different blocks of code based
on the value of an expression.
For Each Statements:
Syntax:
For Each element In collection
' Code to execute for each element in the collection
5)Next
Explanation: Iterates over each element in a collection, such as an array
or a list.
Do While/Do Until Statements:
Syntax:
Do While condition
' Code to execute while the condition is true
Loop
or
Do Until condition
' Code to execute until the condition is true
6)Loop
Explanation: Repeatedly executes a block of code while (or until) a
specified condition is true.
Try...Catch...Finally Statements:
Syntax:
Try
' Code that might cause an exception
Catch ex As Exception
' Code to handle the exception
Finally
' Code that always executes, whether an exception occurred or not
7)End Try
Explanation: Used for error handling. The code in the Try block is
monitored for exceptions, and if one occurs, the corresponding Catch
block is executed.
Exit Statements:
Syntax:
Exit For ' Exits a For loop
Exit While ' Exits a While loop
Exit Sub ' Exits a subroutine
Exit Function ' Exits a function
Explanation: Forces an immediate exit from a loop, subroutine, or
function.

8)Return Statements:
Syntax:
Return expression
Explanation: Exits a function and returns a value to the calling code.

6. Write a program in C# for multiplication of two numbers.


using System;

class Program
{
static void Main()
{
// Input two numbers
Console.Write("Enter the first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter the second number: ");


double num2 = Convert.ToDouble(Console.ReadLine());

// Multiply the numbers


double result = MultiplyNumbers(num1, num2);

// Display the result


Console.WriteLine($"The product of {num1} and {num2} is:
{result}");

// Wait for user input before closing the console window


Console.ReadLine();
}

// Function to multiply two numbers


static double MultiplyNumbers(double x, double y)
{
return x * y;
}
}

7. Write a program in C# to calculate area of a square.


using System;

class Program
{
static void Main()
{
// Input the side length of the square
Console.Write("Enter the side length of the square: ");
double sideLength = Convert.ToDouble(Console.ReadLine());

// Calculate the area of the square


double area = CalculateSquareArea(sideLength);
// Display the result
Console.WriteLine($"The area of the square with side length
{sideLength} is: {area}");

// Wait for user input before closing the console window


Console.ReadLine();
}

// Function to calculate the area of a square


static double CalculateSquareArea(double side)
{
return side * side;
}
}

8. Write a VB .NET program to check given number is palindrome or not.


Module Module1
Sub Main()
' Input a number
Console.Write("Enter a number: ")
Dim number As Integer = Convert.ToInt32(Console.ReadLine())

' Check if the number is a palindrome


If IsPalindrome(number) Then
Console.WriteLine($"{number} is a palindrome.")
Else
Console.WriteLine($"{number} is not a palindrome.")
End If

' Wait for user input before closing the console window
Console.ReadLine()
End Sub

' Function to check if a number is a palindrome


Function IsPalindrome(num As Integer) As Boolean
Dim originalNumber As Integer = num
Dim reversedNumber As Integer = 0

' Reverse the digits of the number


While num > 0
Dim digit As Integer = num Mod 10
reversedNumber = (reversedNumber * 10) + digit
num \= 10
End While

' Check if the reversed number is equal to the original number


Return originalNumber = reversedNumber
End Function
End Module

9. Write a VB.NET program to print Yesterday’s date on screen.


Module Module1
Sub Main()
' Get today's date
Dim todayDate As Date = Date.Now

' Calculate yesterday's date


Dim yesterdayDate As Date = todayDate.AddDays(-1)

' Display yesterday's date on the screen


Console.WriteLine("Yesterday's date: " &
yesterdayDate.ToString("yyyy-MM-dd"))

' Wait for user input before closing the console window
Console.ReadLine()
End Sub
End Module

10.Write a VB.NET program to display Studentid. Student Name and student


course and student fees.
Module Module1
Sub Main()
' Declare variables for student information
Dim studentId As Integer
Dim studentName As String
Dim studentCourse As String
Dim studentFees As Double

' Input student information


Console.Write("Enter Student ID: ")
studentId = Convert.ToInt32(Console.ReadLine())

Console.Write("Enter Student Name: ")


studentName = Console.ReadLine()

Console.Write("Enter Student Course: ")


studentCourse = Console.ReadLine()

Console.Write("Enter Student Fees: ")


studentFees = Convert.ToDouble(Console.ReadLine())

' Display student information


Console.WriteLine("Student Information:")
Console.WriteLine($"Student ID: {studentId}")
Console.WriteLine($"Student Name: {studentName}")
Console.WriteLine($"Student Course: {studentCourse}")
Console.WriteLine($"Student Fees: {studentFees:C}")

' Wait for user input before closing the console window
Console.ReadLine()
End Sub
End Module

11.What are the HTML controls? Explain.


HTML controls, also known as HTML form controls or HTML form elements,
are elements used within HTML forms to collect user input. They allow
users to interact with a web page by providing a way to enter data, make
selections, and submit information. HTML controls play a crucial role in
creating interactive and dynamic web pages. Here are some common HTML
controls:
1)Text Input:
<input type="text">: Allows users to enter a single line of text.

2)Password Input:
<input type="password">: Similar to a text input, but the entered text is
masked for security (useful for passwords).

3)Textarea:
<textarea></textarea>: Allows users to enter multiple lines of text.

4)Checkbox:
<input type="checkbox">: Represents a checkbox that users can check or
uncheck.

5)Radio Button:
<input type="radio">: Represents a radio button, part of a group of radio
buttons where only one can be selected at a time.

6)Select Dropdown:
<select><option></option></select>: Creates a dropdown list, allowing
users to select one option from a list.

7)Button:
<button></button>: Creates a clickable button.

8)Submit Button:
<input type="submit">: Submits the form data to the server.

9)Reset Button:
<input type="reset">: Resets the form to its default values.

10)Image Input:
<input type="image" src="image.jpg">: Uses an image as a submit button.
11)File Input:
<input type="file">: Allows users to upload files.

12)Hidden Input:
<input type="hidden">: Stores data on the form that is not displayed to the
user.

12.Write steps to connect to database using ADO.Net.


Connecting to a database using ADO.NET involves several steps. ADO.NET is
a set of classes in the .NET Framework that provides a way to interact with
data sources such as databases. Here are the general steps to connect to a
database using ADO.NET:

1)Add Reference to System.Data Namespace:


Ensure that your project has a reference to the System.Data namespace,
which contains the ADO.NET classes. You can add this reference by
including Imports System.Data in your code file or by adding a reference to
the System.Data assembly.
Imports System.Data

2)Choose a Data Provider:


ADO.NET supports different data providers for various databases. Choose
the appropriate data provider for your database. Common providers
include:

System.Data.SqlClient for SQL Server


System.Data.OleDb for OLE DB data sources
System.Data.Odbc for ODBC data sources
System.Data.OracleClient for Oracle databases

3)Create a Connection String:


Construct a connection string that contains the necessary information to
connect to your database, such as the server, database name,
authentication details, etc.

Dim connectionString As String = "Data Source=YourServer;Initial


Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword;"
4)Instantiate a Connection Object:
Create an instance of the connection object (SqlConnection,
OleDbConnection, etc.) and set its ConnectionString property.
Dim connection As New SqlConnection(connectionString)

5)Open the Connection:


Open the connection to the database using the Open method.
connection.Open()

6)Perform Database Operations:


Use ADO.NET classes like SqlCommand, SqlDataReader, DataAdapter, etc.,
to execute queries, retrieve data, or perform other database operations.
' Example: Execute a SQL command
Dim command As New SqlCommand("SELECT * FROM YourTable",
connection)
Dim reader As SqlDataReader = command.ExecuteReader()

' Process the results

' Close the reader when done


reader.Close()

7)Close the Connection:


Always close the connection when you're done to free up resources.
connection.Close()

8)Handle Exceptions:
Use try-catch blocks to handle exceptions that may occur during database
operations. Proper error handling is crucial for robust database
connectivity.

Try
' Database operations
Catch ex As Exception
' Handle the exception
Finally
' Close the connection in the finally block to ensure it gets closed even if
an exception occurs
connection.Close()
End Try
9)Dispose of Resources:
Dispose of the connection object and other ADO.NET objects to release
resources explicitly.
connection.Dispose()

13.Explain Common Type Systems (CTS) and Common Language


Specification (CLS).
Common Type System (CTS) and Common Language Specification (CLS) are
integral components of the .NET framework, providing a foundation for
interoperability between different programming languages and ensuring
consistent behavior across diverse environments.

Common Type System (CTS):


1)Definition:
The Common Type System is a standard that specifies how types are
declared, used, and managed in the Common Language Runtime (CLR) of
the .NET framework.
2)Goals:
Enable cross-language integration: CTS facilitates interoperability between
programs written in different languages that target the .NET framework.
Define a set of common data types: It defines a common set of data types
that can be used consistently across languages.
3)Key Features:
Type Definitions: CTS defines a set of common types that can be used
across all .NET languages.
Type Conversion: It provides rules for how data types are converted
between languages.
Type Safety: Ensures type safety by enforcing strict rules for type checking.
Object Lifetime Management: CTS defines rules for object lifetime and
memory management in the CLR.
4)Example:
If you declare an integer variable in C# (int x;), it is the same as declaring it
in VB.NET (Dim x As Integer).

Common Language Specification (CLS):


1)Definition:
The Common Language Specification is a subset of the CTS. It defines a set
of rules that a language must adhere to if it wants to be considered CLS-
compliant.
2)Goals:
Ensure language interoperability: CLS ensures that components written in
one language can be used by components written in another language
within the .NET framework.
Promote code reuse: By adhering to CLS, developers increase the chances
that their code can be used by others.
3)Key Features:
Naming Conventions: CLS defines rules for naming conventions to ensure
consistency across languages.
Data Type Support: Specifies a subset of data types from CTS that should be
used to ensure interoperability.
Exception Handling: Defines guidelines for exception handling to ensure
consistent error handling across languages.
Accessibility: Specifies rules for accessibility of members to ensure that
they are accessible across languages.
4)Example:
CLS-compliant code avoids language-specific features that may not be
supported by all .NET languages. For instance, it discourages language-
specific keywords or features that are not universally supported.

14.Write a program to show list of doctors visiting to “Sahyadri


Multispecialty Hospital”.
using System;
using System.Collections.Generic;

class Doctor
{
public string Name { get; set; }
public string Specialization { get; set; }
public Doctor(string name, string specialization)
{
Name = name;
Specialization = specialization;
}
}

class Program
{
static void Main()
{
// Create a list of doctors
List<Doctor> doctors = new List<Doctor>
{
new Doctor("Dr. John Smith", "Cardiologist"),
new Doctor("Dr. Lisa Johnson", "Orthopedic Surgeon"),
new Doctor("Dr. Emily Davis", "Neurologist"),
// Add more doctors as needed
};

// Display the list of doctors visiting Sahyadri Multispecialty Hospital


Console.WriteLine("List of Doctors visiting Sahyadri Multispecialty
Hospital:");
foreach (var doctor in doctors)
{
Console.WriteLine($"Name: {doctor.Name}, Specialization:
{doctor.Specialization}");
}

// Wait for user input before closing the console window


Console.ReadLine();
}
}
15.Write a program to find prime numbers betn 2 to 20.
using System;

class Program
{
static void Main()
{
Console.WriteLine("Prime numbers between 2 and 20:");

for (int i = 2; i <= 20; i++)


{
if (IsPrime(i))
{
Console.WriteLine(i);
}
}

// Wait for user input before closing the console window


Console.ReadLine();
}

// Function to check if a number is prime


static bool IsPrime(int number)
{
if (number < 2)
{
return false;
}

for (int i = 2; i <= Math.Sqrt(number); i++)


{
if (number % i == 0)
{
return false;
}
}
return true;
}
}

*Each Question 3 Marks


1. Inheritance.
Inheritance is a fundamental concept in object-oriented programming
(OOP) that allows a class to inherit properties and behaviors from
another class. In .NET, which includes languages like C# and VB.NET,
inheritance is a core feature. Here's an overview of inheritance in .NET:

1)Basic Inheritance Syntax:


Inheritance is implemented using the : symbol in the class declaration. A
derived class inherits from a base class, gaining access to its members
(fields, properties, methods, etc.).

csharp
// Base class
public class Animal
{
public string Name { get; set; }

public void Eat()


{
Console.WriteLine("Animal is eating.");
}
}

// Derived class
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
Access Modifiers in Inheritance:
Public members of the base class are accessible in the derived class.
Protected members of the base class are accessible in the derived class.
Private members of the base class are not directly accessible in the
derived class.
Internal members are accessible if the derived class is in the same
assembly.

2)Overriding Methods:
Derived classes can provide their own implementation for a method
already defined in the base class using the override keyword.

csharp
public class Cat : Animal
{
public void Meow()
{
Console.WriteLine("Cat is meowing.");
}

public override void Eat()


{
Console.WriteLine("Cat is eating.");
}
}

3)Abstract Classes and Methods:


An abstract class is a class that cannot be instantiated and may contain
abstract methods. Abstract methods have no implementation in the
base class and must be implemented by any derived class.
csharp
public abstract class Shape
{
public abstract double CalculateArea();
}

public class Circle : Shape


{
public double Radius { get; set; }

public override double CalculateArea()


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

4)Sealed Classes and Methods:


The sealed keyword is used to prevent further inheritance of a class or
method.

csharp
public sealed class FinalClass
{
// Class implementation
}

public class CannotInheritFromFinalClass // This will result in a


compilation error
// : FinalClass
{
// Class implementation
}
Benefits of Inheritance:
Code Reusability: Inheritance allows the reuse of existing code from
base classes, reducing redundancy.
Polymorphism: Derived classes can be treated as instances of their base
class, allowing for polymorphic behavior.

2. ASP.Net server controls.


ASP.NET server controls are components in the ASP.NET framework that
run on the server and encapsulate user-interface and other related
functionality. They are an integral part of building dynamic and
interactive web applications. ASP.NET server controls are similar to
HTML controls but provide additional features, enhanced functionality,
and a consistent programming model. They can be used to create a wide
variety of user interface elements and other functionalities on web
pages.
Here are some common ASP.NET server controls:
1)TextBox:
<asp:TextBox>: Represents a text input control.

2)Button:
<asp:Button>: Represents a button control that can initiate actions when
clicked.

3)Label:
<asp:Label>: Displays static text or can be used to display dynamic text
from the server side.

4)DropDownList:
<asp:DropDownList>: Represents a dropdown list for selecting items.

5)ListBox:
<asp:ListBox>: Represents a list box for selecting multiple items.

6)CheckBox:
<asp:CheckBox>: Represents a checkbox control.

7)RadioButton:
<asp:RadioButton>: Represents a radio button control.

8)Image:
<asp:Image>: Displays an image on the web page.

9)HyperLink:
<asp:HyperLink>: Represents a hyperlink control.

10)GridView:
<asp:GridView>: Represents a tabular data control for displaying data in
a grid.
11)Repeater:
<asp:Repeater>: Represents a data-bound control that can iterate over a
collection of data.

12)Calendar:
<asp:Calendar>: Represents a calendar control for selecting dates.

13)FileUpload:
<asp:FileUpload>: Allows users to upload files to the server.

14)LoginView:
<asp:LoginView>: Represents a control for displaying different content
to users based on their authentication status.

15)Validation Controls:
<asp:RequiredFieldValidator>, <asp:RegularExpressionValidator>, etc.:
Used for client-side and server-side validation of user input.

3. Constructor and Destructor.


Constructors:
Constructor is a special method in a class that is called when an object of
the class is created. Constructors are used to initialize the object's state,
set default values, and perform any other setup that may be required. In
C#, a constructor has the same name as the class and does not have a
return type.

csharp
public class MyClass
{
// Default Constructor
public MyClass()
{
// Initialization code here
}

// Parameterized Constructor
public MyClass(int value)
{
// Initialization code with a parameter
}
}
Default Constructor: It has no parameters and is automatically called
when an object is instantiated.

Parameterized Constructor: It accepts parameters and allows you to


initialize object properties with specific values during instantiation.

Destructors:
Destructor is a special method that is used for cleaning up resources
before an object is destroyed or goes out of scope. In C#, a destructor is
defined using the ~ symbol followed by the class name and has no
parameters or return type. Unlike constructors, destructors are not
called explicitly; they are automatically invoked by the garbage collector.

csharp
public class MyClass
{
// Destructor
~MyClass()
{
// Cleanup code here
}
}
The destructor is called automatically when the garbage collector
determines that there are no references to the object.

It's important to note that in C#, you don't typically need to write
destructors explicitly unless your class manages unmanaged resources
(such as file handles or database connections).

Example:
csharp
using System;
public class MyClass
{
private string message;

// Parameterized Constructor
public MyClass(string msg)
{
message = msg;
Console.WriteLine("Constructor: " + message);
}

// Destructor
~MyClass()
{
Console.WriteLine("Destructor: " + message);
}
}

class Program
{
static void Main()
{
// Create an object and call the constructor
MyClass obj = new MyClass("Hello");

// Do some work with the object

// The destructor will be called automatically when the object is no


longer in scope
}
}

You might also like