Object-Oriented Programming Lab Manual
Object-Oriented Programming Lab Manual
CERTIFICATE
Course Supervisor:
Ms. Saima Sipy
7 Implementing Inheritance in C#
LAB # 01
Object Oriented Programming Lab-Manual
Objective
Introduction to Visual [Link] Integrated Development Environment (IDE)
In this window you will select an appropriate template based on what kind of application you want to
create, and a name and location for your project and solution.
The most common applications are:
• Console Application
• WPF Application
Solution Explorer
Solutions and projects contain items that represent the references, data connections, folders, and
Files that you need to create your application. A solution container can contain multiple projects and
a project container typically contains multiple items.
Object Oriented Programming Lab-Manual
Toolbox
The Toolbox contains all the controls, etc. we can use in our user interface. In order to use them in our user
interface, we just drag and drop them to the “Form”, as shown below:
1. A huge library of code that we can call from our C# programs. This saves us writing
everything ourselves.
2. A “runtime” module, which runs our programs for us when we’re ready (this happens
invisibly - you don't need to worry about it)
Object Oriented Programming Lab-Manual
When you write a C# program (or a program in any of the other .NET languages), you typically call some
code that lives in the library, as well as writing some of your own code.
There are so many classes in the .NET framework, and some of them are pretty complicated, so we
certainly won't try to cover the whole thing here.
A Simple C# Program
This lab will touch on many topics with only a minimum of explanation. Let’s start by looking at a
simple C# program. The complete program source is shown in the top shaded area in Figure [Link]
shown, the code is contained in a text file called [Link].
• Without the using statement in line 1, the compiler wouldn’t have known where to look
for class Console.
Note: Identifiers are case sensitive. For instance, the variable names myVar and MyVar are
different identifiers.
• The starting point of execution of every C# program is at the first instruction in Main.
• The name Main must be capitalized.
Simple Statements
A statement is a source code instruction describing a type or telling the program to perform an
action.
A simple statement is terminated by a semicolon.
Blocks
A block is a sequence of zero or more statements enclosed by a matching set of curly braces; it
acts as a single syntactic statement
Write
Write is a member of the Console class. It sends a text string to the program’s console window.
In its simplest form, Write sends a literal string of text to the window. The string must be enclosed in
quotation marks. The following line of code shows an example of using the Write member:
This code produces the following output in the console window:
This code produces the output that follows. Notice that Write does not append a newline character after
the string, so the output of the three statements runs together on a single line.
Object Oriented Programming Lab-Manual
WriteLine
WriteLine is another member of Console, which performs the same functions as Write, but appends a
newline character to the end of each output string. For example, if you use the preceding code,
substituting WriteLine for Write, the output is on separate lines:
[Link]()
Used to get a value from the user input.
[Link]()
Used to convert a string argument to an integer.
Allows math to be preformed once the string is converted.
Escape Sequences.
Object Oriented Programming Lab-Manual
Tasks
Q # 01 (a) Write the output of the program
using System;
class Addition
{
static void Main( string[] args )
{
string firstNumber, secondNumber;
int number1, number2, sum;
[Link]( "Please enter the first integer: " );
firstNumber = [Link]();
[Link]( "\nPlease enter the second integer: " );
secondNumber = [Link]();
number1 = [Link]( firstNumber );
number2 = [Link]( secondNumber );
sum = number1 + number2;
[Link]( "\nThe sum is {0}.", sum );
}
(b)Output of Block A and Block B are same if it is true then write your findings
Block B Block A
[Link]( "\nPlease enter the second int number1;
integer: " ); [Link]( "Please enter the first integer:
secondNumber = [Link](); " );
number1 = [Link]( firstNumber ); number1 = [Link]( [Link]() );
[Link]( "\nThe sum is {0}.", [Link]( "\nThe sum is {0}.",
Object Oriented Programming Lab-Manual
Q # 02 Write an application that asks the user to enter two numbers, obtains the two numbers
from the user and prints the sum, product, difference and quotient of the two numbers.
Lab # 2
Aim:
Understanding the decision making statements in C#.
Theory:
Decision making structures requires the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false. C# provides following types of decision making
statements.
Statement Description
nested if You can use one if or else if statement inside another if or else
statements if statement(s).
Syntax:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
switch statement A switch statement allows a variable to be tested for equality against a list
of values.
Syntax:
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
nested switch You can use one switch statement inside another switch statement(s).
statements Syntax:
switch(ch1)
{
case 'A':
WriteLine("This A is part of outer switch" );
switch(ch2)
{
case 'A':
WriteLine("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
Object Oriented Programming Lab-Manual
Program:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
else if (a == 20)
{
/* if else if condition is true */
[Link]("Value of a is 20");
}
else if (a == 30)
{
/* if else if condition is true */
[Link]("Value of a is 30");
}
else
{
/* if none of the conditions is true */
[Link]("None of the values is matching");
}
[Link]("Exact value of a is: {0}", a);
[Link]();
}
}
}
Output:
Object Oriented Programming Lab-Manual
Program:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
char grade = 'B';
switch (grade)
{
case 'A':
[Link]("Excellent!");
break;
case 'B':
case 'C':
[Link]("Well done");
break;
case 'D':
[Link]("You passed");
break;
case 'F':
[Link]("Better try again");
break;
default:
[Link]("Invalid grade");
break;
}
[Link]("Your grade is {0}", grade);
[Link]();
}
}
}
Output:
Object Oriented Programming Lab-Manual
Program:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b = 200;
switch (a)
{
case 100:
[Link]("This is part of outer switch ");
switch (b)
{
case 200:
[Link]("This is part of inner switch ");
break;
}
break;
}
[Link]("Exact value of a is : {0}", a);
[Link]("Exact value of b is : {0}", b);
[Link]();
}
}
}
Output:
Object Oriented Programming Lab-Manual
Lab Task:
a. Write a program that determines that number entered by user is even or odd.
b. Write a program which takes user’s input for age and on basis of that input gives the
following output:
If Age is greater than 45 then prints the message “You are old stay at home and wait for
call”
If Age is less than 30 then prints “Hey! Man enjoy your life with your kids”
Use Switch statement in b Task.
c. Write a C# program that takes an integer as amount of money entered to be drawn. If the
amount is less than or equal to current balance, then print message “Amount is available.”
And if the amount entered by the user is greater than current balance, then print the
message “Amount is not available.”
Lab # 3
Aim:
Understanding the Loops in C# and implementing of Loops.
Theory:
A loop statement allows executing a statement or a group of statements multiple times and
following is the general from of a loop statement in most of the programming languages:
Syntax:
while(condition)
{
statement(s);
}
Syntax:
do...while loop It is similar to a while statement, except that it tests the condition at
the end of the loop body
Syntax:
do
{
statement(s);
}while( condition );
nested loops One or more loops inside any another while, for or do..while loop can
be used.
For Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
The flow of control in for loop is like this:
● The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long
as a semicolon appears.
● Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement just
after the for loop.
Object Oriented Programming Lab-Manual
● After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
● The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.
Flow Diagram
Program:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* for loop execution */
for (int a = 10; a < 20; a = a + 1)
{
[Link]("value of a: {0}", a);
}
[Link]();
}
}
}
Output:
namespace nested_loop
{
class Program
{
static void Main(string[] args)
{
int i, j;
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++) //Nested for loop
{
[Link](j);
Object Oriented Programming Lab-Manual
}
[Link]("\n");
}
[Link]();
}
}
}
Output:
Unlike for and while loops, which test the loop condition at the start of the loop,
the do...while loop checks its condition at the end of the loop. A do...while loop is similar
to a while loop, except that a do...while loop is guaranteed to execute at least one time. The
syntax of do…while loop is:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested. If the condition is true, the flow of control jumps back
up to do, and the statement(s) in the loop execute again. This process repeats until the given
condition becomes false.
Program:
Object Oriented Programming Lab-Manual
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
[Link]("value of a: {0}", a);
a = a + 1;
}
while (a < 20);
[Link]();
}
}
}
Output:
Lab Tasks:
c. Write a program using do…while loop that prints sum of four numbers, get input from
user.
d. Write a program using do-while loop that will calculate the sum of every third integer beginning
with i=2, (i.e. sum = 2+5+8+11+….) for values of ‘i’ that are less than 100.
h. Write C# program to prompt user to choose correct answer from given list of answer
choices of a question. (use while loop)
Lab # 4
Aim:
Understanding and implementing Functions/Methods in C#.
Theory:
A method is a group of statements that together perform a task. Every C# program has at least one
class with a method named Main.
To use a method, you need to:
● Define the method
● Call the method
Method Body
}
● Access Specifier: This determines the visibility of a variable or a method from another
class.
● Return type: A method may return a value. The return type is the data type of the value
the method returns. If the method is not returning any values, then the return type is void.
● Method name: Method name is a unique identifier and it is case sensitive. It cannot be
same as any other identifier declared in the class.
● Parameter list: Enclosed between parentheses, the parameters are used to pass and receive
data from a method. The parameter list refers to the type, order, and number of the
parameters of a method. Parameters are optional; that is, a method may contain no
parameters.
● Method body: This contains the set of instructions needed to complete the required
activity.
Public method from other classes can be called by using the instance of the class. For
example, the method FindMax belongs to the NumberManipulatorclass, it can be called from
another class Test.
Mechanism Description
Value parameters This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the argument.
Reference parameters This method copies the reference to the memory location of an
argument into the formal parameter. This means that changes
made to the parameter affect the argument.
Output parameters This method helps in returning more than one value.
Object Oriented Programming Lab-Manual
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
Program:
using System;
namespace SwappApplication
Object Oriented Programming Lab-Manual
{
class SwappingStrings
{
static void SwapStrings(ref string s1, ref string s2)
// The string parameter is passed by reference.
// Any changes on parameters will affect the original variables.
{
string temp = s1;
s1 = s2;
s2 = temp;
[Link]("Inside the method: {0} {1}", s1, s2);
}
Program:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
Object Oriented Programming Lab-Manual
Maths Function in C#
Trignometric Functions
Using System;
class Program
{
static void Main()
{
[Link]([Link](0)); // Inverse cosine
[Link]([Link](2)); // Cosine
[Link]([Link](5)); // Hyperbolic cosine
Absolute Function
An absolute value is not negative. It is the same as the original value but with no negative sign.
The [Link] method in the .NET Framework provides a tested absolute value function. It deals
with certain edge cases.
using System;
class Program
{
static void Main()
{
Object Oriented Programming Lab-Manual
Power
[Link] computes exponential values. It takes the powers of numbers such as by squaring
values. It is a simple and convenient way to compute exponents in the C# language
using system
public class Example
{
public static void Main()
{
double result = [Link](5, 2);
[Link](result);
}
}
Logarithm
The Math class provides logarithms. With the [Link] and Math.Log10 methods in the System
namespace, we compute logarithms with a specific base or base 10.
using System;
class Program
{
static void Main()
{
double a = [Link](1);
[Link](a);
double b = Math.Log10(1000);
[Link](b);
[Link] computes a square root value at runtime. A square root is the number that, when
multiplied by itself, equals the original number. Sqrt is a slower computation. It can be cached for a
performance boost.
using System;
class Program
{
static void Main()
{
// Compute square roots by calling [Link].
double a = [Link](1);
double b = [Link](2);
double c = [Link](3);
double d = [Link](4);
[Link](a);
[Link](b);
[Link](c);
[Link](d);
}
}
Truncate
[Link] eliminates numbers after the decimal. It acts upon a decimal or floating-point
number. It calculate the integral part of a number.
using System;
class Program
{
static void Main()
{
decimal a = 1.223M;
double b = 2.913;
a = [Link](a);
b = [Link](b);
[Link](a);
[Link](b);
}
}
Constant
Math.E is a constant. It is a public float value. It stores the first digits of the base of the natural
logarithm
using System;
class Program
{
static void Main()
{
double e = Math.E; // Get E constant
[Link]("--- Math.E ---");
Object Oriented Programming Lab-Manual
// Write results.
[Link](a);
[Link](b);
}
}
Multiply
[Link] multiplies two large integers. With regular multiplication, as with the star operator,
the result may overflow. BigMul avoids this problem. It returns a long
using System;
class Program
{
static void Main()
{
// Call BigMul.
long product1 = [Link]([Link], [Link]);
// Display values.
[Link](product1);
}
}
Division Remainder
[Link] divides two numbers and returns the remainder. With the division operator we do
not get the remainder in a separate variable. But with [Link] we compute the quotient and
the remainder. We can store them separately.
using System;
class Program
{
static void Main()
{
Object Oriented Programming Lab-Manual
[Link](quotient);
[Link](result);
}
}
Lab Tasks:
a. Write a program that implements function PrintString and prints your name.
b. Write a program that implements PrintFunc and accepts input from user.
h. Write a program in C# Sharp to check whether a given string is Palindrome or not using
recursion.
LAB # 05
OBJECTIVE
Implementation of Class and Object Creation
Overview of Classes
A Class Is an Active Data Structure
A class is a data structure that can store data and execute code. It contains the following:
• Data members, which store data associated with the class or an instance of the class. Data
Members generally model the attributes of the real-world object the class represents.
Object Oriented Programming Lab-Manual
• Function members, which execute code. Function members generally model the functions and
actions of the real-world object the class represents.
A C# class can have any number of data and function members. The members can be any Combination of
nine possible member types. These member types are shown in below Table.
Declaring a Class
The class declaration provides the following:
• The class name
• The members of the class
• The characteristics of the class
Methods
A method is a named block of executable code that can be executed from many different parts of
the program, and even from other programs. When a method is called, or invoked, it executes its
code, and then returns to the code that called it.
Return type: This states the type of value the method returns. If a method does not return a
value, the return type is specified as void.
Name: This is the name of the method.
Parameter list: This consists of at least an empty set of matching parentheses. If there are
parameters), they are listed between the parentheses.
Object Oriented Programming Lab-Manual
Method body: This consists of a matching set of curly braces, containing the executable code.
Class
A class is simply a representation of a type of object. It is the blueprint/ plan/ template that
describe the details of an object. A class is the blueprint from which the individual objects are
created. Class is composed of three things: a name, attributes, and operations.
Declaring Classes
Public class Employee
{
//Fields, properties, methods and events go here...
}
Object Creation
Employee secretary; // declares secretary
secretary = new Employee (); // allocates space
Object-creation expression
The keyword new
Example # 01
using System;
namespace example1
{
class example1
{
public int v = 1;
}
class Program
{
Object Oriented Programming Lab-Manual
Example # 02
using System;
namespace example2
{
class temp
{
public float high;
public float low;
}
}
}
Output Example # 02
Example # 03
using System;
namespace example3
{
class Building
{
public int Floors; // number of floors
public int Area; // total square footage of building
public int Occupants; // number of occupants
}
class BuildingDemo
{
static void Main()
{
Building house = new Building(); // create a Building object
int areaPP; // area per person
[Link] = 4;
[Link] = 2500;
[Link] = 2;
areaPP = [Link] / [Link]; // Compute the area per person.
[Link]("house has:\n " + [Link] + " floors\n " + [Link] + " occupants\n " +
[Link] + " total area\n " + areaPP + " area per person");
[Link]();
}
}
}
Output Example # 03
Object Oriented Programming Lab-Manual
Task
1. Write the output of the following program.
using System;
public class Book
{
public string Title;
public string Author;
public short YearPublished;
public int NumberOfPages;
public char CoverType;
}
public class Exercise
{
static void Main()
{
var First = new Book();
[Link]("Title: ");
[Link]([Link]);
[Link]("Author: ");
[Link]([Link]);
[Link]("Year: ");
[Link]([Link]);
[Link]("Pages: ");
[Link]([Link]);
[Link]("Cover: ");
[Link]([Link]);
[Link]();
}
}
2. Create a class student with a data members name, age, marks of English , marks of math,
marks of science, total marks, obtained marks and percentage provide member functions
CalculateTotalMarks and CalculatePercentage to calculate marks and percentage in
main.
Object Oriented Programming Lab-Manual
3. Write a program that contains a class which has a method that takes user name as input
and second functions which returns number of vowels present in it and Main program
prints the number of vowels
4. Create a rectangle class with two data members’ length and width Provide member
functions to calculate the perimeter and area of the rectangle and a function square
which returns true if the rectangle is a square otherwise it returns false.
LAB # 06
OBJECTIVE
Encapsulation
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical
package'. Encapsulation, in object oriented programming methodology, prevents access to implementation
details. Encapsulation is used to restrict access to the members of a class so as to prevent the user of a
given class from manipulating objects in ways that are not intended by the designer. While encapsulation
hides the internal implementation of the functionalities of class without affecting the overall functioning of
the system, it allows the class to service a request for functionality and add or modify its internal structure
(data or methods) to suit changing requirements. Binding (or wrapping) code and data together into a
single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines...
Access modifiers
Encapsulation in C# is implemented with different levels of access to object data Encapsulation is
implemented by using access specifiers in C#. An access specifier defines the scope and visibility of a class
member. C# supports the following access specifiers:
using System;
namespace Public_Access_Specifiers
{
class access
{
public string name;
public void print()
{
[Link]("\nMy name is "+name);
}
}
class Program
{
static void Main(string[] args)
{
access ac = new access();
[Link]("Enter your name:\t");
[Link] = [Link]();
[Link]();
[Link]();
}
Object Oriented Programming Lab-Manual
}
}
Private Access Specifiers (C#)
The private access specifiers restrict the member variable or function to be called outside from the parent
class. A private function or variable cannot be called outside from the same class. It hides its member
variable and method from other class and methods. However, you can store or retrieve value from private
access modifiers using get set property.
Example: In the following example num2 is not accessible outside the class.
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
int num2;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
ob1.num2 = 20;
[Link]("Number one value in main {0}", ob1.num1);
[Link]();
}
}
}
The above program will give compilation error.
Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in
the form of public, we can declare those fields as private. The Private data are manipulated indirectly by
two ways. Let us see some example programs in C# to demonstrate Encapsulation by those two methods.
The first method is using a pair of conventional accessor and mutator methods. Another one method is
using a named property. Whatever be the method our aim is to use the data without any damage or
change.
Let us see an example of Department class. To manipulate the data in that class (String
departname) we define an accessor (get method) and mutator (set method).
using system;
public class Department
{
Object Oriented Programming Lab-Manual
// Accessor.
public string GetDepartname()
{
return departname;
}
// Mutator.
public void SetDepartname( string a)
{
departname=a;
}
}
Like the above way we can protect the private data from the outside world. Here we use two separate
methods to assign and get the required data.
In the above example we can't access the private data departname from an object instance. We
manipulate the data only using those two methods.
Properties are a new language feature introduced with C#. Only a few languages support this property.
Properties in C# helps in protect a field in a class by reading and writing to it. The first method itself is good
but Encapsulation can be accomplished much smoother with properties.
using system;
public class Department
{
private string departname;
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d= new Department();
[Link]="Communication";
[Link]("The Department is :{0}",[Link]);
return 0;
}
}
From the above example we see the usage of Encapsulation by using properties. The property has two
accessor get and set. The get accessor returns the value of some property field. The set accessor sets the
value of some property field with the contents of "value". Properties can be made read-only. This is
accomplished by having only a get accessor in the property implementation.
[Link]();
[Link]([Link]());
// create a new Program instance and call the two instance methods.
Program programInstance = new Program();
[Link]();
[Link]([Link]());
}
}
Output
Static method
Static method
C
Instance method
Instance method
D
Object Oriented Programming Lab-Manual
Lab Tasks
2. Write a program to explain method in C#. Create a static function factorial() that
accept a number from user and returns factorial of the number.
3. Write a main method for your Vehicle class that creates a few vehicles and prints out their field
values. Make the fields in your Vehicle class private, and add accessor and mutator methods for
the fields.
4. Write a C# code which created a public class Employee with its public member variables name , dept
and designation. Now create method EmpName( ) which takes user input for employee name and
then input the name also. Create another method DeptList( ) that takes input the name of department
of employee and third method as EmpDesig( ) which just takes input about employee’s designation.
In main call these methods and print appropriate results.
5. Write code which creates a class Calculation and declare methods like Add( ) and Subtract( ). Take
two private variables a and b and take user input for these variables that would later be passed to the
appropriate method for calculations.(Use Property)
LAB # 07
Object Oriented Programming Lab-Manual
OBJECTIVE
Implementing Inheritance in C#
Inheritance
Inheritance is a mechanism of extending existing classes without modifying them, thus you can create a
general class that defines traits common to a set of related items. This class can then be inherited by other,
more specific classes, each adding those things that are unique to it.
Inheritance is one of the three foundational principles of object-oriented programming because it allows
the creation of hierarchical classifications
In the language of C#, a class that is inherited is called a base class. The class that does the inheriting is
called a derived class. Therefore, a derived class is a specialized version of a base class. It inherits all of
the variables, methods properties defined by the base class and add its own unique elements.
The idea of inheritance implements the is-a relationship. For example,
General Syntax
SomeClass //Base Class
{
…
} Class-base specification
↓
class OtherClass : SomeClass //Derived Class
{ ↑ ↑
... Colon Base class
}
We can summarize the different access types according to who can access them in the following way:
Access public protected private
Example-1
Object Oriented Programming Lab-Manual
using System;
class Citizen
{
string idNumber = "111-2345-H";
string name = "ABC";
public void GetPersonalInfo()
{
[Link]("Name: {0}", name);
[Link]("ID Card Number: {0}", idNumber);
}
}
class Employee: Citizen
{
string companyName = "Technology Group Inc.";
string companyID = "ENG-RES-101-C";
public void GetInfo()
{
[Link]("Citizen's Information:");
GetPersonalInfo();
[Link]("\nJob Information:");
[Link]("Company Name: {0}", companyName);
[Link]("Company ID: {0}", companyID);
}
}
class MainClass
{
public static void Main()
{
Employee E = new Employee();
[Link]();
}
}
Output
Citizen's Information:
Name: ABC
ID card Number: 111-2345-H
Job Information:
Company Name: Technology Group Inc.
Company ID: ENG-RES-101-C
Multilevel Inheritance
In C# programming, a class be can derived from a derived class which is known as multilevel inheritance
General Syntax:
class A
{}
class B : A
{}
Object Oriented Programming Lab-Manual
class C : B
{}
class D : C
{}
example :
using System;
namespace Multilevel_inheritance
{
class TwoDShape
{
public double width;
public double height;
}
class Triangle : TwoDShape
{
public string style;
public double Area()
{
return width * height / 2;
}
public void ShowStyle()
{
[Link]("Style of Triangle is: " + style);
}
}
class ColorTriangle : Triangle
{
public string color;
public void ShowColor()
{
[Link]("Color Of Triangle is:"+ color);
}
Object Oriented Programming Lab-Manual
}
class Shapes
{
static void Main(string[] args)
{
ColorTriangle c = new ColorTriangle();
[Link]("Enter Width Of Triangle:");
[Link] = [Link]([Link]());
[Link]("Enter Height Of Triangle:");
[Link]= [Link]([Link]());
[Link]("Enter Style Of Triangle:");
[Link] =[Link]();
[Link]("Enter Color Of Triangle:");
[Link] = [Link]();
[Link]("-----------Triangle---------------");
[Link]();
[Link]();
[Link]();
[Link]("Area Of Triangle is: "+ [Link]());
[Link]();
}
}
}
LAB TASK
Q1. Create an inheritance hierarchy that a bank might use to represent customers’ bank accounts.
All customers at this bank can deposit (i.e., credit) money into their accounts and withdraw (i.e., debit)
money from their accounts. More specific types of accounts also exist. Savings accounts, for instance, earn
interest on the money they hold. Checking accounts, on the other hand, charge a fee per transaction (i.e.,
credit or debit).
Create base class Account and derived classes Savings-Account and Checking Account that inherit from
class Account. Base class Account should include
Data member account balance (double)
Member function credit should add an amount to the current balance.
Member function debit should withdraw money from the Account and ensure that the debit
amount does not exceed the Account’s balance. If it does, the balance should be left unchanged
and the function should print the message "Debit amount exceeded account balance."
Member function getBalance should return the current balance.
Derived class SavingsAccount should inherit Account, include
A data member interest rate (percentage) assigned to the Account.
Member function calculateInterest that returns a double indicating the amount of interest earned
by an account.
(Member function calculateInterest should determine this amount by multiplying the interest rate
by the account balance)
Derived class CheckingAccount should inherit Account and include
An additional data member of type double that represents the fee charged per transaction.
Object Oriented Programming Lab-Manual
Member functions credit and debit so that they subtract the fee from the account balance
whenever either transaction is performed successfully.
CheckingAccount’s versions of these functions should invoke the base-class Account version to
perform the updates to an account balance.
CheckingAccount’s debit function should charge a fee only if money is actually withdrawn
(i.e., the debit amount does not exceed the account balance).
LAB # 09
Object Oriented Programming Lab-Manual
Aim:
Theory:
Arrays are collections of data. A scalar variable can hold only one item at a time. Arrays can hold
multiple items. These items are called elements of the array. Arrays store data of the same data
type. Each element can be referred to by an index. Arrays are zero based. The index of the first
element is zero. Arrays are reference types.
A fixed length array can store a predefined number of items.
A dynamic array does not have a predefined size. The size of a dynamic array increases as you add
new items to the array. You can declare an array of fixed length or dynamic. You can even change
a dynamic array to static after it is defined.
In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring
an array, you need to instantiate an array by using the "new" operator. For example, the following
code snippet declares an array that can store 5 items only starting from index 0 to 4.
int[] intArray;
intArray = new int[5];
Declaring Arrays:
Following is the easiest and most used way of declaring arrays in C#:
<type of array or data type> <square brackets> <array name>;
int[] ages;
String[] names;
float[] weights;
The following code snippet defines the simplest dynamic array of integer types that does not have a
fixed size.
int[] intArray;
[Link]();
}
}
Output:
Object Oriented Programming Lab-Manual
Program:
using System;
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
[Link]();
}
}
}
Output:
Lab Tasks:
(a) Write C# code for implementing arrays that accepts user inputs and then displays
them. Take different arrays like this: stringArray, integerArray, doubleArray.
(b) Write a program that adds two arrays and then displays the result. Initialize static
array.
(c) Write a program that adds two arrays and then displays the result. Initialize static
array.
(d) Write a program that takes input from user for intMyArray1 and intMyArray2 and
then adds up these two arrays and stores result in third array inyMyRsultantArr.
The result must also be displayed.
(e) Write a program that displays the elements of array initialized by user after being
multiplied by 2.
(f) Write a program that inputs two arrays from user and then multiply both arrays
and displays result into another array.
(g) Write a program that implements a PrintArray function which displays array being
passed to it. Initialize a string array in Main and then pass it to the function.
LAB # 10
OBJECTIVE
Understanding the concept of Interfaces in C#.
Interface
An interface is a reference type that represents a set of function members, but does not implement them.
Other types—classes or structs—can implement interface
Interfaces are declared by using the interface keyword. Here is a simplified form of an interface
declaration:
Interface name
{
ret-type method-name1(param-list);
ret-type method-name2(param-list);
// ...
ret-type method-nameN(param-list);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To implement an
interface, the name of the interface is specified after the class name in just the same way that a base class
is specified. The general form of a class that implements an interface is shown here:
Classclass-name: interface-name
{
// class-body
}
The name of the interface being implemented is specified in interface-name. When a class implements an
interface, the class must implement the entire interface. It cannot pick and choose which parts to
implement, for example. A class can implement more than one interface. When a class implements more
than one interface, specify each interface in a comma-separated list. A class can inherit a base class and
also implement one or more interfaces. In this case, the name of the base class must come first in the
comma-separated list.
using System;
namespace interfaces
{
interface ISeries
{
int getNext();
void SetStart(int val );
void reset();
}
class ByTwos : ISeries
{
Object Oriented Programming Lab-Manual
}
}
class InterfaceDemo
{
static void Main(string[] args)
{
ByTwos obj1 = new ByTwos();
for (int i = 0; i < 5; i++)
{
[Link]("Next Value is " + [Link]());
}
[Link]("Reseting:");
[Link]();
for (int i = 0; i < 5; i++)
{
[Link]("Next Value is " + [Link]());
}
Next value is 8
Next value is 10
Resetting
Next value is 2
Next value is 4
Next value is 6
Next value is 8
Next value is 10
nStarting at 100
Next value is 102
Next value is 104
Next value is 106
Next value is 108
Next value is 110
using System;
using [Link];
using [Link];
using [Link];
namespace interfaces
{
interface IGetSum
{
void getSum();
}
interface ICalSum
{
int calSum(int a,int b);
}
class Addition:IGetSum,ICalSum
{
int sum;
public int calSum(int a,int b)
{
sum=a+b;
return sum;
}
public void getSum()
{
[Link]("Sum is :"+sum);
}
}
class InterfaceDemo
{
Object Oriented Programming Lab-Manual
class InterfaceDemo
{
static void Main(string[] args)
{
test t = new test();
((IA)t).display();
((IB)t).display();
[Link]();
}
}
}
LAB TASK
1. Write a program to demonstrates the multiple inheritance
Object Oriented Programming Lab-Manual
1. Create an interface Itransaction contain void showTransaction(), double getAmount() ,Create class
Transaction that inherit Itransaction and contains private string tCode; private string date;
private double amount; add default constructor and parametric constructor to initialize values and
implement void showTransaction(), double getAmount()in class.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace LAB10
{
interface Itransaction
{
void showTransaction(); double getAmount();
}
class Transaction : Itransaction
{
string Code; string date; double amount;
public Transaction()
{
}
public Transaction(string Code, string date, double amount)
{
[Link] = Code; [Link] = date; [Link] = amount;
}
public double getAmount()
{
[Link]("Enter amount");
amount = [Link]([Link]());
return amount;
}
public void showTransaction()
{
[Link]("Enter transaction code");
Code = [Link]();
[Link]("Enter date of transaction");
date = [Link]();
}
public void show()
{
[Link]("The tcode is " + Code);
[Link]("The date is " + date);
[Link]("The amount is " + amount);
}
}
using System;
using [Link];
using [Link];
Object Oriented Programming Lab-Manual
using [Link];
using [Link];
namespace LAB10
{
interface Itransaction
{
void showTransaction(); double getAmount();
}
class Transaction : Itransaction
{
string Code; string date; double amount;
public Transaction()
{
}
public Transaction(string Code, string date, double amount)
{
[Link] = Code; [Link] = date; [Link] = amount;
}
public double getAmount()
{
[Link]("Enter amount");
amount = [Link]([Link]());
return amount;
}
public void showTransaction()
{
[Link]("Enter transaction code");
Code = [Link]();
[Link]("Enter date of transaction");
date = [Link]();
}
public void show()
{
[Link]("The tcode is " + Code);
[Link]("The date is " + date);
[Link]("The amount is " + amount);
}
}
Object Oriented Programming Lab-Manual
3. Create an interface Itransaction contain void showTransaction(), double getAmount() ,Create class
Transaction that inherit Itransaction and contains private string tCode; private string date;
private double amount; add default constructor and parametric constructor to initialize values and
implement void showTransaction(), double getAmount()in class.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace LAB10
{
interface Itransaction
{
void showTransaction(); double getAmount();
}
class Transaction : Itransaction
{
string Code; string date; double amount;
public Transaction()
{
}
public Transaction(string Code, string date, double amount)
{
[Link] = Code; [Link] = date; [Link] = amount;
}
public double getAmount()
{
[Link]("Enter amount");
amount = [Link]([Link]());
return amount;
}
public void showTransaction()
{
[Link]("Enter transaction code");
Code = [Link]();
[Link]("Enter date of transaction");
date = [Link]();
}
public void show()
{
[Link]("The tcode is " + Code);
[Link]("The date is " + date);
[Link]("The amount is " + amount);
}
}
class Program
{
static void Main(string[] args)
{
Transaction obj = new Transaction();
obj = new Transaction("0",
"0", 0);
Object Oriented Programming Lab-Manual
4. Write C# code for implementing interface ‘IAnimal’ which declares a method AName( ) in it and
then class InterImp implements this method being inherited from interface IAnimal. Method
AName will simply print the name of the animal like “ I am a cat and my name is:” +name.
using System;
using
[Link];
using [Link];
using [Link];
using [Link];
namespace LAB10
{
interface IAnimal
{
void Aname();
}
class InterImp : IAnimal
{
string name;
public
InterImp()
{
}
public InterImp(string name)
{
[Link] = name;
}
public void Aname()
{
[Link]("\n\t\tI am a Cat and my name is {0}", name);
}
class Program
{
static void Main(string[] args)
{
InterImp obj = new
InterImp(); obj = new
InterImp("jenny");
[Link]();
[Link]();
}
}
}
}
OUTPUT:
Object Oriented Programming Lab-Manual
5. Update the above program by taking user input in method AName( ). Input the type of animal
whether dog or cat and then the name of the animal. Then this method will be implemented in
inherited class.
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace LAB10
{
static void Main(string[]
{
int s; string x;
[Link]("What
{
interface IAnimal
{
void Aname1(); void Aname2();
}
class InterImp : IAnimal
{
string name; public InterImp()
{
}
public InterImp(string a)
{
name = a;
}
public void Aname1()
{
[Link]("\n\t\t It is a Cat and its name is {0}", name);
}
public void Aname2()
{
Q-6 Write a program that implements an interface for AC and declares two methods ACOn( ) and ACOff( ).
Both the methods will print apprpiate messages of “AC Off” or “AC On” when implemented and called in
inherited class ACInterImp.
using System;
using
[Link];
using [Link];
using [Link]; class Program
using [Link]; {
static void Main(string[]
namespace LAB10
{ {
interface IAC
{ args) int s;
string
x;
[Link]("What
void is the Name of your AC?");
ACoff(); x =
void ACon(); [Link]();
ACInterImp obj = new
} ACInterImp(
class ACInterImp : ); obj = new
IAC ACInterImp(x);
{ [Link]("Ar
e
string name; You Feeling Hot?");
public [Link]("[Link]
ACInterImp() s
{ ");
[Link]("2.
} No")
public ACInterImp(string ; s =
a)
{ [Link]([Link]());
name = a; if (s == 2)
[Link]("\n\t\t [Link]();
Your is off"); }
AC
} [Link](
);
public void ACon() }
{ }
[Link]("\n\t\t }
Your is on Enjoy!"); }
AC
}
Object Oriented Programming Lab-Manual
6. Write a program that implements interface IShape that declares method SName that inputs name
of shape from user and also method ShArea that calculates area of shape. [hint: method for area
calculation will implement if-then-else and compare the input with shape string to calculate area of
a specific shape.]
using System; }
using else
[Link]; {
using [Link]; [Link]("What
using [Link];
using [Link]; is the lenght of your shape ?");
l1 =
namespace LAB10 [Link]([Link](
{ ));
interface IShape1 [Link]("Wh
{ at is the breadth of
void your shape?");
Sname(); b1 =
void [Link]([Link](
ShArea(); ));
} area = l1 * b1;
class shape : IShape1 [Link]("T
{ he
string Area of Rectangle is {0}", area);
to; int }
s; }
int l1; class Program
int b1; {
int static void Main(string[]
area; args)
public shape() {
{ } int s;
public shape(string t, int string
a) th;
{ [Link]("Wh
to = at is your shape
t; s = name?");
a;
} [Link]("[Link]
public void Sname()
{ ");
[Link]("\n\
t\t Your shape is {0}", to); [Link]("[Link]");
} s =
public void ShArea() [Link]([Link](
{ ));
if (s == 2) [Link]("Al
{ so Write the name of your
[Link]("Wh shape");
at is the lenght of th =
your shape ?"); [Link]();
l1 = shape obj = new
[Link]([Link]( shape(); obj = new
)); shape(th, s);
area = l1 * l1; [Link]();
[Link]("T [Link]();
he [Link](
Area of Square is {0}", area); );
Object Oriented Programming Lab-Manual
}
}
}
}
Object Oriented Programming Lab-Manual
LAB # 11
OBJECTIVE
To create your first Windows form project, click the File menu again. This time, select New Project from
the menu. When you do, you'll see the New Project dialogue box again. This one in C# 2010:
The obvious difference from the Console Application you created in the previous section is the blank Form
in the main window. Notice the Toolbox, though, on the left hand side. We'll be adding controls from the
Toolbox to that blank Form1 you can see in the image above. If you can't see the Toolbox, you may just
see the Tab, as in the following image:
Object Oriented Programming Lab-Manual
If your screen looks like the one above, move your mouse over to the Toolbox tab. It will expand to look
like the first one. If you want to permanently display the Toolbox, click on the pin symbol:
Notice the Solution Explorer on the right side of your screen. (If you can't see the Solution Explorer, click
its entry on the View menu at the top of Visual C# Express.) If you compare it with the Solution Explorer
when you created your Console Application, you'll see there's only one difference - the Form.
It's in Designer view that we'll be adding things like buttons and text boxes to our form. But you can run
this programme as it is. From the Debug menu at the top, click Start Debugging (Or you can just press the
F5 key on your keyboard.):
To add a control to a form, you can use the Toolbox on the left of Visual Studio. Move your mouse over to
the Toolbox, and click the plus symbol next to Common Controls. You should see the following list of
things that you can add to your form:
Object Oriented Programming Lab-Manual
Click the Button item under the Common Controls heading. This will select it. Now click once anywhere
on your form.
(You can also hold down your left mouse button and drag out a button to the size you want it.)
A button is something you want people to click on. When they do, the code you write gets executed. The
text on the button, which defaults to "button1", can be changed. You can add anything you like here, but
it should be something that's going to be useful for your users, such as "Open a text file", or "Calculate
Now".
The controls you add to a form have something called Properties. A property of a control is things like its
Height, its Width, its Name, its Text, and a whole lot more besides. To see what properties are available
for a button, make sure the button is selected, as in the image below:
If a control is selected, it will have white squares surrounding it. If your button is not selected,
simply click it [Link] view the list of Properties in alphabetical order, click the AZ symbol at
the top, circled in red in the image below:
Object Oriented Programming Lab-Manual
As you can see, there's a lot of Properties for a button. Scroll down to the bottom and
locate the Text Property:
The Text Property, as its name suggests, is the Text you want to appear on the button. At
the moment, it says button1. Click inside of the text area of button1. Delete the default
text:
A Message
The Text part of your Properties Window will then look like this:
Now press the enter key on your keyboard. Have a look at your Form, and the Text on the
button should have changed:
Object Oriented Programming Lab-Manual
There's a few more Properties we can change before we get to the code.
The first number, 75, is the width of the button. The second number, 23, is the height of the
button. The two numbers are separated by a comma. Change the numbers to 100, 30:
Press the enter key again, and the size of your button will change:
You can move your button around the Form by clicking it with the left mouse button to
select it. Hold down you left mouse button and drag your button around the form.
Object Oriented Programming Lab-Manual
The only difference from the last time you saw this screen is the addition of the code for the button. This
code:
This is just another Method, a piece of code that does something. The name of the Method
isbutton1_Click. It's called button1 because that's currently the Name of the button. When you changed
the Text, Location, and Size properties of the button, you could have also changed the Name property
from button1 (the default Name) to something else.
The _Click part after button1 is called an Event. Other events are MouseDown, LocationChanged,
TextChanged, and lots more.
Run your programme by clicking Debug > Start Debugging. Or just press the F5 key on your keyboard.
Your programme will look like this:
Object Oriented Programming Lab-Manual
When your line of code looks like the one above, Run your programme again. Click your button
and you should see a Title on your Message Box:
MessageBoxButtons
Double click the one for YesNo, and it will be added to your code.
Run your programme again, and click your button. Your Message Box will then look like this:
Object Oriented Programming Lab-Manual
MessageBoxIcon
Name: btnStrings
Location: 90, 175
Size: 120, 30
Text: Get Text Box Data
A Label is just that: a means of letting your users know what something is, or what it is for. To add a
Label to the form, move your mouse over to the Toolbox on the left. Click the Label item under
Common Controls:
Object Oriented Programming Lab-Manual
Change the following properties of your label, just like you did for the button:
Location: 10, 50
Text: Name
You don't really need to set a size, because Visual C# will automatically resize your label to fit your text.
But your Form should look like this:
Move your mouse back over to the Toolbox. Click on the TextBox entry. Then click on your form. A new
Text Box will be added, as in the following image:
Object Oriented Programming Lab-Manual
Instead of setting a location for your text box, simply click it with your left mouse button. Hold your left
mouse button down, and the drag it just to the right of the Label.
Notice that when you drag your text box around, lines appear on the form. These are so that you can
align your text box with other controls on the form. In the image below, we've aligned the text box with
the left edge of the button and the top of the Label.
Back to the button code, though. We're going to set up a string variable. To do this, you need two things:
The Type of variable you want, and a name for your variable.
string
firstName;
firstName = [Link];
[Link](firstName);
Object Oriented Programming Lab-Manual
Exercise-1
Exercise-2
LAB # 12
Working with WindowsForm II
Property Description
Appearance The radio button can be displayed as a normal button,or a circular button with a label beside it.
CheckAlign Determines the alignment of the button. The default isMiddleLeft, which will show the buttonto
the left of the label.
Checked When set to true, the radio button will be inits "ON" state and a dot will beseen inside the
button.
Text Sets the text inside the label of the radio button.
Drag two radio buttons to the form. Name them radioButtonYes and radioButtonNo. Drag a button control, name
it buttonShow, and set its text to Show Message.
Double click the buttonShow to generate a handler for its Click event. Write the highligted code inside the event
handler.
private void buttonShow_Click(object sender, EventArgs e)
{
if ([Link])
[Link]("You choosed yes!");
else
[Link]("You choosed no!");
}
CheckBox Control
The CheckBox control ([Link]) is also a type of button and apears as an empty box
with a label beside it. By default, when the empty box is clicked, a check will show up inside the box telling that the
checkbox control is in its "checked" state. Unlike a radio button, you can check multiple or even all of the
checkboxes. The CheckBox control contains similar properties as the radio button control. The following are some
properties that are exclusive to the CheckBox control.
Property Description
Checked Determines if the check box is checked.
Object Oriented Programming Lab-Manual
The following example demonstrates the use of the CheckBox control. Create a form and drag a label, three
checkboxes and a button. Change the texts of the controls and align them properly as seen below.
Name the checkboxes checkBoxSoap, checkBoxShampoo, and checkBoxToothpaste respectively. Name the button
buttonCheckOut. No need to name the label since we are not using it in our code. Double click the button and copy
the following type the following code inside the event handler.
string items = [Link];
if ([Link])
items += "\n Soap";
if ([Link])
items += "\n Shampoo";
if ([Link])
items += "\n Toothpaste.";
[Link]("You have bought: " + items);
Launch the program and select some items by checking them. As you check the item, they will be added to the list
that will be shown when you click the Check Out button.
Object Oriented Programming Lab-Manual
The GroupBox control is a similar control but allows you to add captions for each group. You do that by using the Text property
of the GroupBox control. The GroupBox control also has a default border.
ComboBox Control
The ComboBox control is another way of allowing a user to choose from a set of options. The ComboBoxcontrol looks like a text
box with a button in its right side. When the button is clicked, the ComboBox show a drop-down box containing the list of
options/items available. The user can then choose from these options by clicking one of them. The selected option will then be
the text inside the ComboBox. The following are some of the properties of the ComboBox control.
Property Description
DropDownHeight The height in pixels of the drop-downbox in a combo box.
FormatString The format specifier characters that indicate how a value is to be displayed.
Items The items in the combo box.
Sorted Specifies whether the items on the combo box should be sorted.
Text The default text when there is no item selected.
SelectedIndex Gets or sets the selected index. Every item has an index starting from 0 to (number of items - 1). A value
of -1 indicates that no item is selected.
SelectedItem Gets or sets the item of the currently selected item.
Event Description
Click Occurs when the component is clicked.
DropDown Occurs when the drop-down portion of the combo box is shown
DropDownClosed Indicates that the drop-down portion of the combo box has been closed.
SelectedIndexChanged Occurs when the value of the SelectedIndex property is changed.
Object Oriented Programming Lab-Manual
The following example shows the basic functionality of a ComboBox control. Place a combo box on a blank form. Name
it comboBoxNames by changing the Name property. Go to the Properties Window and find the Items property. You should see
a button with three dots in it. Click it to open the String Collection Editor. Alternatively, you can click Edit Items located below
the list of properties in the Properties [Link] the String Collection Editor, type the names show in the figure below then
press OK.
Change the Text property of the combo box to "Choose a name" so it will have a default text when no name is chosen.
Run the program and choose a name. The program will greet the name you have selected immediately after you
selected that name.
DateTimePicker Control
The DateTimePicker control ([Link]) is used to pick a single date. The control appears by
default, as a combo box with a calendar icon at the right part. You can select each date component and such as the month and
use the arrow keys to adjust individual components.
The DateTimePicker control shows (by default) the current date or the selected date. By clicking the calendar icon
during runtime, you will be presented with a calendar where you can choose dates.
You can change the format of the date displayed using the Format property. You can use the Long, Short,Time, or
Custom formats. When the Custom format is selected, you can specify a format string in the
control's CustomFormat property. For example, setting the format to MM-dd-yy shows the date using the month
number, the date, and the last two digits of the year where each date component is separated with dashes.
Example output would be 04-08-11.
The ShowCheckBox property shows indicates whether to show a checkbox at the left side of the control.
Object Oriented Programming Lab-Manual
When the check box is checked, you can select date or time components and modify them using the arrow keys. If
the check box is unchecked, then you are not allowed to do that. Clicking the dropdown button that shows the
calendar checks the checkbox. The state of the check box can be accessed using the Checkedproperty.
The ShowUpDown property transforms the dropdown button into an up-down button and hides the calendar icon as
shown by the following screen shot.
TabControl
The TabControl control ([Link]) allows you to create tabbed windows that you can
see in many applications. An example of a tabbed window are the properties window of files and the tabs in Visual
Studio.
To add a tab control, go to the Containers category of the toolbox and find the TabControl. Drag it to the form. You
can resize the control but perhaps the best way is to use the Dock property so it will always take up the whole
space of the form. You can go to the Properties window and find the Dock property. Click the drop down then click
the middle button which means that the TabControl will be docked to all side of the form.
Object Oriented Programming Lab-Manual
The TabPage Collection Editor allows you to add and remove tabs and change properties such as the text of
individual tabs. You can add controls to individual containers of the tab. For example, drag some controls to the
body of the first tab. Then you can click on the second tab in the Designer and you can add another set of controls
for that tab.
Property Description
Alignment The area (top, bottom, left, right) where the tabs are aligned. The default is top.
Appearance The appearance of the control's tabs.
ImageList Contains a list of images that will be displayed for each tab.
ItemSize Specifies the size of the tab.
Multiline Allows you to create multiple rows of tabs.
SelectedIndex Specifies the index of the selected tab page.
SelectedTab Gets or sets the selected tab.
TabCount Returns the number of TabPages of the TabControl.
TabPages Allows you to access the tab pages of the TabControl and add or remove tab pages.
Tab Index
You can cycle the focus of each control by pressing the tab key on the keyboard. Each control has
a TabIndexproperty which indicates the order each control will get focus when the tab key is pressed. It is
important to monitor the TabIndex of each control and make sure that they are in sequence depending on the
layout of the control. Consider a form with four text boxes.
Suppose that their TabIndex properties are not in sequence such as this.
Object Oriented Programming Lab-Manual
TextBox TabIndex
txtFirstNa
1
me
txtLastNam
4
e
txtGender 3
txtAge 2
When you run the program, the focus will be on the control who has the lowest tab index. So therefore, the focused
control will be txtFirstName. If you press tab, the focus will go to the control which has the next TabIndex.
Therefore, txtAge will receive the focus
ToolTip
You can use the ToolTip control ([Link]) to display tooltips which offers description
about the certain control of part of the GUI. Tooltips can be seen in numerous applications including Visual Studio.
Tooltips give you a brief description to the functionality of a certain GUI component or control.
You can find the ToolTip control in the common controls category. When you drag a ToolTip control from the
toolbox to the form, you will find it in the component tray section of the Designer.
Once a tooltip is placed, you need to assign it to a control. Whenever a tool tip is added to the form, a new property
named ToolTip is added to every control in the form. You can find it in the properties window.
Task
Design following form, using controls discussed in lab manual
Object Oriented Programming Lab-Manual
}
private void button1_Click(object sender, EventArgs e)
{
string n1 = [Link](textBox1);
string n2 = [Link](textBox2);
Form2 form = new Form2();
[Link]();
}
}
}
CODE FOR [Link]
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
Object Oriented Programming Lab-Manual
namespace WindowsFormsApp266666
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
[Link][Design]
[Link][Design]
LAB # 13
Objective: Database and Database connectivity in C# using Microsoft Sql Server
Accessing Data from a database is one of the important aspects of any programming language. It
is an absolute necessity for any programming language to have the ability to work with
databases. C# is no different.
It can work with different types of databases. It can work with the most common databases such
as Oracle and Microsoft SQL Server.
It also can work with new forms of databases such as MongoDB and MySQL.
We will look at working the Microsoft SQL Server as our database. We are using the Microsoft
SQL Server Express Edition, which is a free database software provided by Microsoft.
In working with databases, the following are the concepts which are common to all databases.
Object Oriented Programming Lab-Manual
1. Connection – To work with the data in a database, the first obvious step is the
connection. The connection to a database normally consists of the below-mentioned
parameters.
1. Database name or Data Source – The first important parameter is the database
name to which the connection needs to be established. Each connection can only
work with one database at a time.
2. Credentials – The next important aspect is the username and password which needs
to be used to establish a connection to the database. It ensures that the username and
password have the necessary privileges to connect to the database.
3. Optional parameters - For each database type, you can specify optional
parameters to provide more information on how .net should handle the connection
to the database. For example, one can specify a parameter for how long the
connection should stay active. If no operation is performed for a specific period of
time, then the parameter would determine if the connection has to be closed.
2. Selecting data from the database – Once the connection has been established, the next
important aspect is to fetch the data from the database. C# can execute 'SQL' select
command against the database. The 'SQL' statement can be used to fetch data from a
specific table in the database.
3. Inserting data into the database – C# can also be used to insert records into the
database. Values can be specified in C# for each row that needs to be inserted into the
database.
4. Updating data into the database – C# can also be used to update existing records into
the database. New values can be specified in C# for each row that needs to be updated
into the database.
5. Deleting data from a database – C# can also be used to delete records into the database.
Select commands to specify which rows need to be deleted can be specified in C#.
Username – sa
Password – demo123
We will see a simple Windows forms application to work with databases. We will have a simple
button called "Connect" which will be used to connect to the database.
Step 1) The first step involves the creation of a new project in Visual Studio. After launching
Visual Studio, you need to choose the menu option New->Project.
Object Oriented Programming Lab-Manual
Step 2) The next step is to choose the project type as a Windows Forms application. Here, we
also need to mention the name and location of our project.
1. In the project dialog box, we can see various options for creating different types of
projects in Visual Studio. Click the Windows option on the left-hand side.
2. When we click the Windows options in the previous step, we will be able to see an option
for Windows Forms Application. Click this option.
3. We then give a name for the application which in our case is "DemoApplication". We
also need to provide a location to store our application.
4. Finally, we click the 'OK' button to let Visual Studio to create our project.
Step 3) Now add a button from the toolbox to the Windows form. Put the text property of the
Button as Connect. This is how it will look like
Step 4) Now double click the form so that an event handler is added to the code for the button
click event. In the event handler, add the below code.
Object Oriented Programming Lab-Manual
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace DemoApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = @"Data Source=WIN-50GP30FGO75;Initial Catalog=Demodb;User
ID=sa;Password=demol23";
cnn = new SqlConnection(connetionString);
[Link]();
[Link]("Connection Open !");
[Link]();
}
}
} Output:-
Object Oriented Programming Lab-Manual
When you click on "connect" button, from the output, you can see that the database connection
was established. Hence, the message box was displayed.
1. A table called demotb. This table will be used to store the ID and names of various
Tutorials.
2. The table will have 2 columns, one called "TutorialID" and the other called
"TutorialName."
3. For the moment, the table will have 2 rows as shown below.
TutorialID
TutorialName
1 C#
2 [Link]
Step 1) Let's split the code into 2 parts so that it will be easy to understand.
The first will be to construct our "select" statement, which will be used to read the data
from the database.
We will then execute the "select" statement against the database and fetch all the table
rows accordingly.
Object Oriented Programming Lab-Manual
Step 2) In the final step, we will just display the output to the user and close all the objects
related to the database operation.
When the above code is set, and the project is run using Visual Studio, you will get the below
output. Once the form is displayed, click the Connect button.
Output:-
From the output, you can clearly see that the program was able to get the values from the
database. The data is then displayed in the message box.
TutorialID TutorialName
1 C#
2 [Link]
Let's change the code in our form, so that we can insert the following row into the table
TutorialID TutorialName
3 [Link]
Object Oriented Programming Lab-Manual
So let's add the following code to our program. The below code snippet will be used to insert an
existing record in our database.
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
If you go to SQL Server Express and see the rows in the demotb table, you will see the row
inserted as shown below
C# Update Database
Just like Accessing data, C# has the ability to update existing records from the database as well.
To showcase how to update records into our database, let's take the same table structure which
was used above.
TutorialID TutorialName
1 C#
2 [Link]
3 [Link]
Let's change the code in our form, so that we can update the following row. The old row value is
TutorialID as "3" and Tutorial Name as "[Link]". Which we will update it to "[Link]
complete" while the row value for Tutorial ID will remain same.
Old row
TutorialID TutorialName
3 [Link]
New row
Object Oriented Programming Lab-Manual
TutorialID TutorialName
3 [Link] complete
So let's add the following code to our program. The below code snippet will be used to update an
existing record in our database.
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
If you actually go to SQL Server Express and see the rows in the demotb table, you will see the
row was successfully updated as shown below.
Deleting Records
Just like Accessing data, C# has the ability to delete existing records from the database as well.
To showcase how to delete records into our database, let's take the same table structure which
was used above.
TutorialID TutorialName
1 C#
Object Oriented Programming Lab-Manual
2 [Link]
3 [Link] complete
Let's change the code in our form, so that we can delete the following row
TutorialID TutorialName
3 [Link] complete
So let's add the following code to our program. The below code snippet will be used to delete an
existing record in our database.
When the above code is set, and the project is executed using Visual Studio, you will get the
below output. Once the form is displayed, click the Connect button.
Output:-
If you actually go to SQL Server Express and see the rows in the demotb table, you will see the
row was successfully deleted as shown below.
Object Oriented Programming Lab-Manual
So, you can have 2 textboxes in a windows form. You can then link one text box to the
TutorialID field and another textbox to the TutorialName field. This linking is done in the Visual
Studio designer itself, and you don't need to write extra code for this.
Visual Studio will ensure that it writes the code for you to ensure the linkage works. Then when
you run your application, the textbox controls will automatically connect to the database, fetch
the data and display it in the textbox controls. No coding is required from the developer's end to
achieve this.
We are going to create 2 textboxes on the windows form. They are going to represent the
Tutorial ID and Tutorial Name respectively. They will be bound to the Tutorial ID and
TutorialName fields of the database accordingly.
Step 1) Construct the basic form. In the form drag and drop 2 components- labels and textboxes.
Then carry out the following substeps
Below is the how the form would look like once the above-mentioned steps are performed.
Step 2) The next step is to add a binding Navigator to the form. The binding Navigator control
can automatically navigate through each row of the table. To add the binding navigator, just go
to the toolbox and drag it to the form.
Object Oriented Programming Lab-Manual
Step 3) The next step is to add a binding to our database. This can be done by going to any of the
Textbox control and clicking on the DataBindings->Text property. The Binding Navigator is
used to establish a link from your application to a database.
When you perform this step, Visual Studio will automatically add the required code to the
application to make sure the application is linked to the database. Normally the database in
Visual Studio is referred to as a Project Data Source. So to ensure the connection is established
between the application and the database, the first step is to create a project data source.
The following screen will show up. Click on the link- "Add Project Data Source". When you
click on the project data source, you will be presented with a wizard; this will allow you to
define the database connection.
Step 4) Once you click on the Add Project Data Source link, you will be presented with a wizard
which will be used to create a connection to the demotb database. The following steps show in
detail what needs to be configured during each step of the wizard.
1. In the screen which pops up , choose the Data Source type as Database and then click on
next button.
2. In the next screen, you need to start the creation of the connection string to the database.
The connection string is required for the application to establish a connection to the
Object Oriented Programming Lab-Manual
database. It contains the parameters such as server name, database name, and the name of
the driver.
1. Click on the New connection button
2. Choose the Data Source as Microsoft SQL Server
3. Click the Continue button.
4. In this screen, we will confirm all the settings which were carried on the previous
screens.
1. Choose the option "Yes" to include sensitive data in the connection string
2. Click on the "Next" button.
5. In the next screen, click on the "Next" button to confirm the creation of the connection
string
Object Oriented Programming Lab-Manual
6. In this step,
1. Choose the tables of Demotb, which will be shown in the next screen.
2. This table will now become an available data source in the C# project
When you click the Finish button, Visual Studio will now ensure that the application can query
all the rows in the table Demotb.
Step 5) Now that the data source is defined, we now need to connect the TutorialID and
TutorialName textbox to the demotb table. When you click on the Text property of either the
TutorialID or TutorialName textbox, you will now see that the binding source to Demotb is
available.
For the first text box choose the Tutorial ID. Repeat this step for the second textbox and choose
the field as TutorialName. The below steps shows how we can navigate to each control and
change the binding accordingly.
2. In the Properties window, you will see the properties of the TutorialID textbox. Go to the
text property and click on the down arrow button.
3. When you click the down arrow button, you will see the demotbBinding Source option.
And under this, you will see the options of TutorialName and TutorialID. Choose the
Tutorial ID one.
Repeat the above 3 steps for the Tutorial Name text box.
Step 6) Next we need to change the Binding Source property of the BindingNavigator to point to
our Demotb data source. The reason we do this is that the Binding Navigator also needs to know
which table it needs to refer to.
Object Oriented Programming Lab-Manual
The Binding Navigator is used to select the next or previous record in the table. So even though
the data source is added to the project as a whole and to the text box control, we still need to
ensure the Binding Navigator also has a link to our data source. In order to do this, we need to
click the Binding navigator object, go to the Binding Source property and choose the one that is
available
Next, we need to go to the Properties window so that we can make the change to Binding Source
property.
When all of the above steps are executed successfully, you will get the below-mentioned output.
Output:-
Now when the project is launched, you can see that the textboxes automatically get the values
from the table.
Object Oriented Programming Lab-Manual
When you click the Next button on the Navigator, it automatically goes to the next record in the
table. And the values of the next record automatically come in the text boxes
C# DataGridView
Data Grids are used to display data from a table in a grid-like format. When a user sees's table
data, they normally prefer seeing all the table rows in one shot. This can be achieved if we can
display the data in a grid on the form.
C# and Visual Studio have inbuilt data grids, this can be used to display data. Let's take a look at
an example of this. In our example, we will have a data grid, which will be used to display the
Tutorial ID and Tutorial Name values from the demotb table.
Step 1) Drag the DataGridView control from the toolbox to the Form in Visual Studio. The
DataGridView control is used in Visual Studio to display the rows of a table in a grid-like
format.
Step 2) In the next step, we need to connect our data grid to the database. In the last section, we
had created a project data source. Let's use the same data source in our example.
1. First, you need to choose the grid and click on the arrow in the grid. This will bring up
the grid configuration options.
2. In the configuration options, just choose the data source as demotbBindingSource which
was the data source created in the earlier section.
Object Oriented Programming Lab-Manual
If all the above steps are executed as shown, you will get the below-mentioned output.
Output:-
From the output, you can see that the grid was populated by the values from the database.
Task:
Make C# application with database connectivity and perform 4 basic function of add, delete,
update and select of database.
Visual Studio's project data sources simplify database connectivity by providing wizards and tools to define connection strings and bind controls to data fields. This enables seamless integration between C# applications and databases, automating data retrieval and manipulation without extensive manual coding, thus boosting productivity .
C# properties succinctly encapsulate getter and setter methods, providing a more intuitive interface for accessing and modifying class fields while ensuring data integrity. They maintain encapsulation by allowing controlled access to the private data fields, unlike traditional getter and setter methods which can be verbose and error-prone .
Passing parameters by reference is beneficial when you need to modify the caller's original data or want to return multiple values from a method. This method allows for efficient memory usage and precise data manipulation, as seen in swapping operations where changes should reflect outside the method's scope .
Encapsulation in C# improves data management by using properties with get and set accessors to control access to class fields. This allows fields to be protected and ensures that data can be read or written only in controlled ways, preventing accidental or unauthorized modifications and increasing code maintainability and flexibility .
The interface ITransaction in C# declares methods that ensure any implementing class follows a specific contract for transactions. It provides a means to show transaction details and retrieve amounts. By enforcing these methods, it ensures consistent behavior across different transaction types, allowing for flexibility and scalability in managing multiple transaction implementations .
Using static classes in C# implies that all its members have to be static. This design choice is suitable for utility classes that provide shared functions which do not depend on instance-specific data. It simplifies code reuse and maintenance but prevents inheritance and instance creation, which can reduce flexibility .
Static methods are considered faster than instance methods because they do not have the overhead of object instantiation. They are associated with the class itself rather than any object, enabling quicker access and saving memory, particularly useful in utility classes where a method should not depend on an object's state .
Interfaces in C# provide polymorphism by allowing different classes to implement the same set of methods defined in an interface, thereby supporting multiple method behaviors. In the IAnimal implementation, classes can define different versions of the AName method, showcasing polymorphic behavior, as the method can vary based on the object's class implementing the interface .
Recursion allows a method to call itself, which can simplify complex problems like calculating factorials or traversing data structures. It's particularly advantageous when problems can be divided into similar subproblems, making the code more intuitive and easier to manage. However, recursive solutions should be used carefully to avoid issues like stack overflow .
The Math class in C# provides a range of static methods for advanced mathematical functions like trigonometric calculations, exponentiation, and logarithms. Its static nature means these methods can be accessed without creating instances of the Math class, optimizing memory and time efficiency. This makes it invaluable for scenarios requiring high-precision calculations .