0% found this document useful (0 votes)
18 views21 pages

C# Programming Lab Experiments Guide

Uploaded by

Imran Shaikh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views21 pages

C# Programming Lab Experiments Guide

Uploaded by

Imran Shaikh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A

Lab Record

.NET FRAMEWORK AND PROGRAMMING


(BCSP-701)
Session: - 2023-24

Department of Computer Science and Engineering

Submitted to Submitted by
Mr. Girish Bisht Akash Giri
Assistant professor 200120101012
EXPERIMENT-1

Aim: Write a program to implement SET, GET properties.

PROGRAM

Using System;
class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}

class Program
{
static void Main(string[] args)
{
Person obj1 = new Person();
[Link] = "Aakash";
[Link]([Link]);
}
}

OUTPUT:

Aakash

Press enter key to exit..


EXPERIMENT-3

Aim: Write a program to print the Armstrong Number.

PROGRAM

using System;
public class ArmstrongExample
{
public static void Main(string[] args)
{
int n,r,sum=0,temp;
[Link]("Enter the Number= ");
n = [Link]([Link]());
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
[Link]("Armstrong Number.");
else
[Link]("Not Armstrong Number.");
}
}
OUTPUT:
EXPERIMENT-4

Aim: Create a console application to calculate area of circle. Accept radius from user
and print [Link] and console application to build simple calculator, calculator will
have following functions Accept 2 numbers perform Add/Sub/Multi and print result.

Program for area of circle:

using System;
class Circle{
static void Main(string[] args){
[Link]("Enter Radius: ");
double rad = [Link]([Link]());
double area = [Link] * rad * rad;
[Link]("Area of circle is: " + area);
}
}

OUTPUT:

Program to implement calculator:

class Program
{
static void Main(string[] args){
int num1;
int num2;
string operand;
ConsoleKeyInfo status;
float answer;
while (true)
{
[Link]("Please enter the first integer: ");
num1 = Convert.ToInt32([Link]());
[Link]("Please enter the second integer: ");
num2 = Convert.ToInt32([Link]());
[Link]("Please enter an operand (+, -, /, *): ");
operand = [Link]();
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
[Link]([Link]() + " " + operand + " " + [Link]() + " = "
+
[Link]());
[Link]("\n\n Do You Want To Break (Y/y)");
status = [Link]();
if([Link]==ConsoleKey.Y)
{
break;
}
[Link]();
}
}
}

OUTPUT:
EXPERIMENT-5

Aim: Write a program to Use a Exception (Predefined and User defined).

PROGRAM

using System;
public class InvalidAgeException : Exception{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException{
static void validate(int age){
if (age < 18){
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args){
try {
Validate(19);
validate(12);
}
catch (InvalidAgeException e) { [Link](e); }
}
}
OUTPUT
EXPERIMENT-6

Aim: Write a program to implement the concept of Abstract and Sealed classes.

Implementation of abstract classes:

PROGRAM

using System;
public abstract class Animal
{
public abstract string Sound { get; }
public virtual void Move()
{
[Link]("Moving...");
}
}

public class Cat : Animal


{
public override string Sound => "Meow";

public override void Move()


{
[Link]("Walking like a cat...");
}
}

public class Dog : Animal


{
public override string Sound => "Woof";
public override void Move()
{
[Link]("Running like a dog...");
}
}

class Program
{
static void Main(string[] args)
{
Animal[] animals = new Animal[] { new Cat(), new Dog() };
foreach (Animal animal in animals)
{
[Link]($"The {[Link]().Name} goes {[Link]}");
[Link]();
}
}
}

OUTPUT :

Implementation of Sealed Classes

PROGRAM

using System;
sealed class SealedClass {
public int Add(int a, int b){
return a + b;
}
}

class Program {
static void Main(string[] args){
SealedClass slc = new SealedClass();
int total = [Link](6, 4);
[Link]("Total = " + [Link]());
}
}

OUTPUT:
EXPERIMENT-7

Aim: Write a program to implement [Link] database connectivity.

PROGRAM

using System;
using [Link];
namespace AdoNetConsoleApplication
{
class Program{
static void Main(string[] args)
{
new Program().Connecting();
}
public void Connecting()
{
using (
SqlConnection con = new SqlConnection(“datasource=.;
database=student; integrated security=SSPI”)
)
{
[Link]();
[Link]("Connection Established Successfully");
}
}
}
}
OUTPUT:
EXPERIMENT-8

Aim: Write a program to implement the concept of Data streams.

PROGRAM

using System;
using [Link];
public sealed class Program{
public static void Main(){
using (Stream s = new FileStream(@"c:\A\[Link]", [Link]))
{
int obj;
while ((obj = [Link]()) != -1)
{
[Link]("{0} ", (char)obj);
}
[Link]();
}
}
}
EXPERIMENT-9

Aim: Write a program to implement the events and delegates.

Implementation of Events:

PROGRAM

using System;
namespace SampleApp {
public delegate string MyDel(string str);
class EventProgram {
event MyDel MyEvent;
public EventProgram() {
[Link] += new MyDel([Link]);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
static void Main(string[] args) {
EventProgram obj1 = new EventProgram();
string result = [Link]("This is event 1");
[Link](result);
}
}
}

OUTPUT:
Implementation of Delegates:

PROGRAM

using System;
class Program{
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);

//Add method
public void sum(int a, int b){
[Link]("(100 + 40) = {0}", a + b);
}

// subtract method
public void subtract(int a, int b){
[Link]("(100 - 60) = {0}", a - b);
}

public static void Main(String []args)


{
Program obj = new Program();
addnum del_obj1 = new addnum([Link]);
subnum del_obj2 = new subnum([Link]);

del_obj1(100, 40);
del_obj2(100, 60);
}
}

OUTPUT:
EXPERIMENT-11

Aim: Write a program to implement Indexers.

PROGRAM

using System;
public class MyCollection{
private int[] data = new int[10];
public int this[int index, bool square]{
get
{
if (square)
return data[index] * data[index];
else
return data[index];
}

set
{
if (square)
data[index] = (int)[Link](value);
else
data[index] = value;
}
}

public int this[string name]


{
get
{
switch ([Link]())
{
case "first":
return data[0];
case "last":
return data[[Link] - 1];

default:
throw new ArgumentException("Invalid index parameter.");

}
}
}

// Read-only indexer
public int this[int index]
{
get { return data[index]; }

}
}

public class Program


{
public static void Main()
{
MyCollection collection = new MyCollection();
collection[0, false] = 5;
collection[1, false] = 10;
collection[2, false] = 15;
collection[3, false] = 20;

[Link](collection[0, false]);
[Link](collection[1, true]);
[Link](collection["first"]);
[Link](collection["last"]);
// Getting values using read-only indexer
[Link](collection[2]);
[Link]();
}
}

OUTPUT:
EXPERIMENT-2

Aim: Write a program to implement string using Array.

PROGRAM

using System;
class Program {
static void Main(string[] args) {
int[] numbers = {1,2,3,4,5,6,7,8};
[Link]("Element in first index : " + numbers[0]);
[Link]("Element in second index : " + numbers[1]);
[Link]("Element in third index : " + numbers[2]);
[Link]("Element in fourth index : " + numbers[3]);
[Link]("Element in five index : " + numbers[4]);
[Link]();
}
}

OUTPUT:
EXPERIMENT-10

Aim: Design the WEB base Database connectivity Form by using ASP. NET.

PROGRAM:

1. Setting up the Project:


Create an [Link] Web Application project in Visual Studio.

2. Designing the Database Connectivity Form (Web Form):

<!DOCTYPE html>
<html>
<head>
<title>Database Connectivity Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Database Connectivity Form</h2>
<label for="txtName">Name:</label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br /><br />

<label for="txtEmail">Email:</label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br /><br />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />


</div>
</form>
</body>
</html>

3. Implementing Database Connectivity (Code-behind):

using System;
using [Link];
using [Link];

namespace YourNamespace
{
public partial class Default : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
// You can add code here that executes when the page loads
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Retrieve form data
string name = [Link];
string email = [Link];

// Database connection string


string connectionString =
[Link]["YourConnectionString"].ConnectionString;

// Insert data into the database


using (SqlConnection connection = new SqlConnection(connectionString))
{
string query = "INSERT INTO YourTableName (Name, Email) VALUES (@Name, @Email)";
SqlCommand command = new SqlCommand(query, connection);
[Link]("@Name", name);
[Link]("@Email", email);

try
{
[Link]();
int rowsAffected = [Link]();
if (rowsAffected > 0)
{
[Link]("Data inserted successfully!");
}
}
catch (Exception ex)
{
[Link]("Error: " + [Link]);
}
}
}
}
}
Table of Contents

S. No. Experiment Name Date Signature


01 WAP to implement SET, Get Properties?

02 WAP to implement String Using array's?


03 WAP to print the ARMSTRONG Number?

04 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.
05 WAP to Use a Exception (Predefined and User
defined).
06 WAP to implement the concept of Abstract and
Sealed Classes.

07 WAP to implement [Link] Database


connectivity.

08 WAP to implement the concept of Data


Streams.
09 WAP to implement the Events and
Delegates.

10 Design the WEB base Database connectivity


Form by using ASP. NET.

11 WAP to implement Indexers.

Common questions

Powered by AI

Encapsulation is a core principle of object-oriented programming that allows restricting direct access to some components of an object and can prevent accidental interference with the logical integrity of the object . In C#, properties are used to implement encapsulation by providing a way to control access to the instance variables of a class. By using 'get' and 'set' accessors, you can manage how an object's properties are read, written, or changed, ensuring data integrity and hiding the internal state of objects from the outside world . For example, the 'Name' property manages access to the private string 'name' in the 'Person' class, allowing controlled manipulation of 'name' through defined interfaces .

Managing data efficiently using streams in C# involves several best practices tailored to optimize performance and resource use. Firstly, utilizing buffered streams can enhance read and write operations by reducing the number of I/O operations, which is critical for large data handling . Secondly, leveraging asynchronous streams enables non-blocking operations, which can significantly improve the responsiveness of applications, especially in I/O-bound scenarios. Thirdly, employing memory streams for temporary data storage can eliminate the need for disk I/O, enhancing speed when manipulating data in memory . Lastly, properly closing and disposing of stream objects is crucial to release I/O resources timely and minimize resource leaks.

ASP.NET provides a robust framework for designing web-based database connectivity forms, offering numerous advantages. It facilitates the integration of advanced server-side capabilities coupled with a wide choice of controls for form building, making database operations seamless and efficient . Additionally, ASP.NET's built-in data handling capabilities can help manage complex data transactions and validation with minimal effort. The framework's support for Model-View-Controller (MVC) and other architectural patterns allows developers to create maintainable and testable applications that can be easily updated or expanded. Furthermore, ASP.NET's efficient session handling and security features enhance the reliability and safety of web applications .

Data access frameworks like ADO.NET offer a layer of abstraction over manual SQL commands, providing significant advantages in terms of ease of use and performance. ADO.NET's object-oriented approach simplifies the handling of connections, data readers, and commands, allowing developers to interact with data in a more structured and effective manner than using raw SQL, which requires explicit string handling and result sets management . Performance-wise, ADO.NET offers features like connection pooling and command execution optimization, which can enhance the speed and efficiency of database operations compared to manual SQL commands that may vary widely in implementation quality. However, manual SQL might still provide flexibility and specificity in complex queries or when working with legacy systems not fully supported by data access frameworks .

Indexers in C# allow objects to be indexed like arrays, providing a more intuitive syntax for accessing data contained within a class or a collection. They allow objects to be accessed similarly to how arrays are accessed, by using an index, offering elegance and simplicity in managing collections within objects . A practical advantage of indexers is that they abstract the method of accessing data, encouraging clean and minimalistic code by using array-like syntax rather than explicit method calls for getting or setting values . They can greatly increase readability and ease of use, especially when dealing with collections encapsulated in classes.

Delegates and events in C# work together to facilitate a decoupled communication pattern, which is essential for developing responsive and dynamic applications. Delegates are type-safe function pointers that can encapsulate references to methods with a specific signature, which allows methods to be passed as parameters or assigned to variables . This provides flexibility in how methods are called and invoked at runtime. Events, built upon delegates, enable classes to notify subscribed listeners when something of interest occurs, following the publisher/subscriber model . Combining delegates with events empowers developers to implement callback techniques that respond to user actions or other triggers without tightly coupling the event source to the listeners, promoting modular and manageable code architecture .

Abstract classes in C# are meant to be base classes from which other classes are derived. They can include abstract methods without body implementations, which derived classes must implement . They are useful when you want to create a generic template for derived classes. In contrast, sealed classes cannot be inherited and are used to restrict further derivation, ensuring that the class implementation is final and unalterable by extending it . Abstract classes are ideal for providing common functionalities in a class hierarchy, while sealed classes are suited for scenarios where a definitive, non-modifiable implementation is needed.

ADO.NET is critical for developers as it provides a powerful framework for accessing and managing data from diverse sources using .NET applications. It facilitates communication with databases, supports a variety of database operations, and provides a rich set of features for handling data-oriented tasks . ADO.NET's disconnection capability allows data manipulation without continuous connection constraints, enhancing application performance. Developers use ADO.NET to establish connections, execute commands, and retrieve or modify data in a consistent manner, promoting data layer abstraction and integration across various database platforms .

Developers should prefer sealed classes when they need to provide a final implementation that should not be inherited or altered further. This is useful in security-critical or performance-sensitive applications where extending classes might compromise the integrity or efficiency of the system . Sealed classes enforce stricter design constraints, ensuring the consistency of behavior and state throughout the lifecycle of the application. Conversely, abstract classes are preferable when creating a common base with shared definitions and multiple implementations that can be extended and customized across different derived classes . Abstract classes suit scenarios that benefit from a flexible inheritance-based architecture.

Exception handling in C# provides a structured way to handle runtime errors, ensuring the program can gracefully recover from unexpected states . Using predefined exceptions, developers can throw and catch standard exceptions thrown by .NET, such as divide by zero or null reference exceptions, which ensures consistency with common error-handling mechanisms . User-defined exceptions provide flexibility to create and handle specific errors unique to application logic, allowing developers to enforce domain-specific constraints and error messages. This enhances code robustness, maintainability, and provides a more accurate and informative feedback mechanism for debugging and logging purposes .

You might also like