Practical 1
1. WAP to implement SET, Get Properties?
using System;
class Person
{
private string name; // Private field to store the name
// Property with a 'get' accessor to retrieve the name
public string GetName
{
get
{
return name;
}
}
// Property with a 'set' accessor to update the name
public string SetName
{
set
{
name = value;
}
}
}
class Program
{
static void Main()
{
Person person = new Person();
// Set the name using the 'SetName' property
person.SetName = "John Doe";
// Get the name using the 'GetName' property
string retrievedName = person.GetName;
Console.WriteLine("Name: " + retrievedName); // Output: Name: John Doe
}
}
Output :
"Name: John Doe"
Practical 2
2. WAP to implement String Using array’s?
using System;
class StringUsingArray
{
private char[] characters;
public StringUsingArray(string input)
{
characters = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
characters[i] = input[i];
}
}
public override string ToString()
{
return new string(characters);
}
}
class Program
{
static void Main()
{
StringUsingArray myString = new StringUsingArray("Hello, .NET");
Console.WriteLine("Custom String: " + myString); // Output: Custom String: Hello, .NET
}
}
Output :
"Custom String: Hello, .NET"
Practical 3
3. WAP to print the ARMSTRONG Number?
using System;
class ArmstrongNumbers
{
// Function to check if a number is an Armstrong number
static bool IsArmstrong(int num)
{
int originalNumber = num;
int numDigits = (int)Math.Floor(Math.Log10(num) + 1);
int sum = 0;
while (num > 0)
{
int digit = num % 10;
sum += (int)Math.Pow(digit, numDigits);
num /= 10;
}
return sum == originalNumber;
}
static void Main()
{
int start = 1;
int end = 1000;
Console.WriteLine("Armstrong numbers in the range from {0} to {1}:", start, end);
for (int i = start; i <= end; i++)
{
if (IsArmstrong(i))
{
Console.WriteLine(i);
}
}
}
}
Output :
Armstrong numbers in the range from 1 to 1000:
1
2
3
4
5
6
7
8
9
153
370
371
407
Practical 4
4. Create a console application to calculate area of circle. Accept radius from user
Calculate circle area and print it Create a console application to build simple
calculator Calculator will have following functions Accept 2 numbers Perform
Add/Sub/Div/Mult Print Result.
using System;
class Program
{
static void Main()
{
Console.WriteLine("Welcome to the Circle Area Calculator and Simple Calculator");
Console.WriteLine("1. Calculate Circle Area");
Console.WriteLine("2. Simple Calculator");
Console.Write("Enter your choice (1/2): ");
if (int.TryParse(Console.ReadLine(), out int choice))
{
if (choice == 1)
{
Console.Write("Enter the radius of the circle: ");
if (double.TryParse(Console.ReadLine(), out double radius))
{
double area = Math.PI * Math.Pow(radius, 2);
Console.WriteLine("The area of the circle is: " + area);
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number for the radius.");
}
}
else if (choice == 2)
{
Console.WriteLine("Simple Calculator");
Console.WriteLine("1. Add");
Console.WriteLine("2. Subtract");
Console.WriteLine("3. Multiply");
Console.WriteLine("4. Divide");
Console.Write("Enter your choice (1/2/3/4): ");
if (int.TryParse(Console.ReadLine(), out int calculatorChoice))
{
Console.Write("Enter the first number: ");
if (double.TryParse(Console.ReadLine(), out double num1))
{
Console.Write("Enter the second number: ");
if (double.TryParse(Console.ReadLine(), out double num2))
{
double result = 0.0;
switch (calculatorChoice)
{
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 != 0)
result = num1 / num2;
else
Console.WriteLine("Error: Division by zero");
break;
default:
Console.WriteLine("Invalid choice. Please select 1, 2, 3, or 4.");
break;
}
Console.WriteLine("Result: " + result);
}
else
{
Console.WriteLine("Invalid input for the second number.");
}
}
else
{
Console.WriteLine("Invalid input for the first number.");
}
}
else
{
Console.WriteLine("Invalid choice. Please select 1, 2, 3, or 4.");
}
}
else
{
Console.WriteLine("Invalid choice. Please select 1 or 2.");
}
}
else
{
Console.WriteLine("Invalid choice. Please select 1 or 2.");
}
}
}
Output :
Welcome to the Circle Area Calculator and Simple Calculator
1. Calculate Circle Area
2. Simple Calculator
Enter your choice (1/2): 2
Simple Calculator
1. Add
2. Subtract
3. Multiply
4. Divide
Enter your choice (1/2/3/4): 1
Enter the first number: 23
Enter the second number: 22
Result: 45
Practical 5
5. WAP to Use a Exception (Predefined and User defined).
using System;
// User-defined exception class
class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
class Program
{
static void Main()
{
try
{
// Example 1: Divide by zero - Predefined exception
int numerator = 10;
int denominator = 0;
int result = numerator / denominator; // This will throw a System.DivideByZeroException
Console.WriteLine("Result: " + result); // This line will not be executed
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Predefined Exception: " + ex.Message);
}
try
{
// Example 2: Custom exception
int age = -5; // Negative age, which is not valid
if (age < 0)
{
throw new CustomException("Invalid age. Age cannot be negative.");
}
}
catch (CustomException ex)
{
Console.WriteLine("User-defined Exception: " + ex.Message);
}
Console.WriteLine("Program continues after exceptions.");
}
}
Output :
Predefined Exception: Attempted to divide by zero.
User-defined Exception: Invalid age. Age cannot be negative.
Program continues after exceptions.
Practical 6
6. WAP to implement the concept of Abstract and Sealed Classes.
using System;
// Abstract class with an abstract method
abstract class Shape
{
// Abstract method that must be implemented by derived classes
public abstract double CalculateArea();
}
// Sealed class that cannot be inherited from
sealed class Circle : Shape
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public override double CalculateArea()
{
return Math.PI * Math.Pow(radius, 2);
}
}
// Attempt to inherit from a sealed class (will result in a compilation error)
// class DerivedCircle : Circle { }
class Program
{
static void Main()
{
// Create an instance of the sealed class
Circle circle = new Circle(5.0);
double area = circle.CalculateArea();
Console.WriteLine("Area of the circle: " + area);
// Attempt to create an instance of a derived class from the sealed class (commented out)
// DerivedCircle derivedCircle = new DerivedCircle();
}
}
Output :
Area of the circle: 78.53981633974483
Practical 7
7. WAP to implement ADO.Net Database connectivity.
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// Connection string for your SQL Server database
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;User
ID=YourUser;Password=YourPassword";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("Connected to the database.");
// SQL query to retrieve data
string query = "SELECT * FROM YourTable";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
Console.WriteLine("Data from the database:");
while (reader.Read())
{
Console.WriteLine("ID: " + reader["ID"] + " | Name: " + reader["Name"]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
Output :
Connected to the database.
Data from the database:
ID: 1 | Name: John
ID: 2 | Name: Jane
ID: 3 | Name: Bob
…
Practical 8
8. WAP to implement the concept of Data Streams.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "sample.txt"; // Replace with the path to your text file
try
{
using (StreamReader reader = new StreamReader(filePath))
{
Console.WriteLine("Reading data from the file:");
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
"sample.txt" file
Hello, this is line 1.
This is line 2.
And here's line 3.
Output :
Reading data from the file:
Hello, this is line 1.
This is line 2.
And here's line 3.
Practical 9
9. WAP to implement the Events and Delegates.
using System;
// Define a delegate with the same signature as the event handler
public delegate void EventHandler(string message);
// Publisher class that contains an event
class Publisher
{
public event EventHandler MyEvent;
public void RaiseEvent(string message)
{
Console.WriteLine("Event raised with message: " + message);
MyEvent?.Invoke(message); // Invoke the event
}
}
// Subscriber class that subscribes to the event
class Subscriber
{
public void HandleEvent(string message)
{
Console.WriteLine("Subscriber received the message: " + message);
}
}
class Program
{
static void Main()
{
Publisher publisher = new Publisher();
Subscriber subscriber = new Subscriber();
// Subscribe to the event
publisher.MyEvent += subscriber.HandleEvent;
// Raise the event
publisher.RaiseEvent("Hello from the publisher!");
Console.WriteLine("Program finished.");
}
}
Output :
Event raised with message: Hello from the publisher!
Subscriber received the message: Hello from the publisher!
Program finished.
Practical 10
10. Design the WEB base Database connectivity Form by using ASP.NET.
Create a new ASP.NET Web Application project in Visual Studio.
Add a connection string to your database in the Web.config file. Replace
"YourConnectionString" with your actual connection string.
<connectionStrings>
<add name="MyDbConnection" connectionString="YourConnectionString" />
</connectionStrings>
Create an ASP.NET web page (e.g., "Default.aspx") and add the following code to the
.aspx file:
<!DOCTYPE html>
<html>
<head runat="server">
<title>Database Connectivity Form</title>
</head>
<body>
<form id="form1" runat="server">
<h1>Database Connectivity Form</h1>
<div>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True"></asp:GridView>
</div>
</form>
</body>
</html>
In the code-behind file (e.g., "Default.aspx.cs"), add the C# code to retrieve data from the
database and bind it to the GridView:
using System;
using System.Data;
using System.Data.SqlClient;
namespace WebDatabaseConnection
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectionString =
System.Configuration.ConfigurationManager.ConnectionStrings["MyDbConnection"].Connection
String;
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable",
connection))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Replace "YourTable" with the name of the table you want to query.
Run the application, and you'll see a web page with a grid view that displays data
from your database.
Practical 11
11. WAP to implement Indexers.
using System;
class MyCollection
{
private string[] data = new string[5];
// Indexer
public string this[int index]
{
get
{
if (index >= 0 && index < data.Length)
return data[index];
else
return null; // Handle out-of-range index
}
set
{
if (index >= 0 && index < data.Length)
data[index] = value;
// Ignore if index is out of range
}
}
}
class Program
{
static void Main()
{
MyCollection collection = new MyCollection();
// Set values using the indexer
collection[0] = "Item 1";
collection[1] = "Item 2";
collection[2] = "Item 3";
// Access values using the indexer and display the output
for (int i = 0; i < 5; i++)
{
string item = collection[i];
if (item != null)
Console.WriteLine($"Item at index {i}: {item}");
else
Console.WriteLine($"Index {i} is out of range.");
}
}
}
Output :
Item at index 0: Item 1
Item at index 1: Item 2
Item at index 2: Item 3
Index 3 is out of range.
Index 4 is out of range.