C-Prog - TextBook by Khan Sir

Download as pdf or txt
Download as pdf or txt
You are on page 1of 164

1

Chapter #1: Introduction to .NET

1.1 Basics of Visual Studio 2010

.NET is a platform to design and develop different application; it comes bundled in the form of
visual studio. Visual Studio 2010 is more than just the next version of Visual Studio to use
with the next version of the .NET Framework. Visual Studio 2010 continues Microsoft’s
attempt to position Visual Studio as a tool we can use for the upstream and downstream
development activities that sandwich actual code writing. For example, we can use Visual
Studio to visually model the entities we want to create in code. Unlike other modeling tools
that have only a one-way relationship between the model and the code generation, our code
stays synchronized with the model.

Visual Studio 2010 is a complete rewrite of the user interface, but the familiar commands and
tools that we have come to know and love are still there. We will notice a completely revised,
intuitive, and modern
user interface that showcases the tremendous leaps that Visual Studio has made since the
release of Visual Studio .NET back in 2002.
Visual Studio 2010 provides a dizzying array of editors, controls, designers, and supporting
tools for developing software.

The programming languages of .NET: The four languages that Microsoft Visual studio
2010 offers (in addition to dozens more that are available from third parties):
❖ VB.NET (Visual Basic)
❖ C#
❖ C++
❖ F# (New programming language)
In this book we are using C# language for developing the following three types of
applications:

❖ Console Applications
❖ Windows applications
❖ ASP.NET Web Applications

.NET is a well known platform for developing console, windows and the web application. It is
one of the best products of Microsoft after windows. .NET runs on the windows and the web
applications run on the IIS server of windows which comes inbuilt with windows operating
system. The best thing about .NET is that we can use different languages for any of the
application according to our convenience and can design and run the program in the same

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
2

window without any other editor; because it has a great IDE for designing and developing
many different application using different languages.

1.2 Introduction to .NET Environment (IDE)

.NET has the best IDE (Integrated Development Environment) for developing any types of
application; IDE is the platform where we can design, code and run the application without
the support of other application. .NET IDE includes following components to develop and run
the application:

• Solution Explorer
• Properties Window
• Tool Box
• Server Explorer
• Form/class/webpage(designing and coding area)
• Menu Bar
• Tool Bar

Solution Explorer: solution explorer list the project name (namespace), program and
supporting files and folders.

Properties Window: properties window list the properties and events of the selected control
or form.

Tool Box: toolbox contains all types of controls like button, textbox, list box, container, menu
& toolbars etc.

Server Explorer: Server explorer list the database connection and database details.

Form/Class/Web Page: this place is actually user interface to design and code for the
specific application, if we work with windows application form will be user interface to design

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
3

and code, for console application class code will be there and for web application web page
will be in the centre to work with it.

Menu Bar: Menu Bar contains several options to do many operation related to development.

Tool Bar: Toolbar contains the short cut of most usable option to support development and
execution of the application.

1.3 .NET Versions:


Six versions of .NET have been released. Each of these versions represents a
milestone in developing software with .NET:

Version 1.0: Released in 2002 with the Visual Studio .NET integrated development
environment. In version 1.0, all development — whether Windows-based or Web-based, and
regardless of the language — was
integrated into Visual Studio. Prior to the release of .NET, each Microsoft
development tool was a separate product.
The object-oriented language C# was created as part of .NET. Visual
Basic was completely revamped to be object oriented. Many Visual
Basic developers felt betrayed, and Microsoft has had a hard time convincing
them to make the leap.
Data access was greatly simplified with ADO.NET, and ASP.NET was
introduced for developing Web applications. Even though these technologies
share the same names as their predecessors (ADO and ASP), the
resemblance stops there. Like all .NET technologies, ADO.NET and ASP.
NET is object oriented.

Version 1.1:

Released in 2003 with Visual Studio .NET 2003. With version 1.1 of .NET, many 1.0 features
that either weren’t ready yet (such as the Compact Framework for devices such as the
PocketPC) or were available separately from Visual Studio (such as ASP.NET) were
completely integrated into Visual Studio .NET 2003. Version 1.1 was more stable and more
widely accepted. During this time, the Microsoft .NET brand became diluted from overuse.

Version 2.0:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
4

Released in October 2005 with Visual Studio 2005. In the two years between the release of
versions 1.1 and 2.0, the dot-net community as the collective of .NET developers is often
called — busily wrote applications that demonstrated how powerful .NET could be. Microsoft
listened, and many of the suggestions for ways to extend .NET, which were written about in
articles on Web sites such as www.gotdotnet.com and www.4guysfromrolla.com, were
implemented as new features in the 2.0 version of .NET

Version 3.0:

Released in November 2006 with the Windows Vista OS.

Version 3.0 combined version 2.0 with four new technologies:

Windows Presentation Foundation (WPF): Gave developers the capability to create much
richer applications by providing better controls. It helped separate the user interface (UI) from
the business logic. It also assisted developers who wanted a consistent UI between desktop
applications and Web-based applications.

Windows Communication Foundation (WCF): Provided easier and more robust


communications between connected systems. It is built on the Web services technology.

Windows Workflow Foundation (WF): Enabled developers to create workflows by using a


new XML-based language named XAML.

Windows CardSpace: This security framework helped users to manage identities that can
be used in transactions such as Web site logins.

Version 3.5:

Released in October 2007 with Visual Studio 2008. Version3.5 builds incrementally on
version 3.0. In addition, it adds the following: Language Integrated Query (LINQ) Integrated
use of Asynchronous JavaScript and XML (AJAX) Full support for WF, WCF, and WPF

Version 4.0: Released in April 2010 with Visual Studio 2010. Version 4.0 builds on version
3.5 and adds the following:

Parallel processing

Entity Framework Support for cloud computing

The F# programming language

Version 4.5:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
5

Visual Studio 2012 Beta was released on February 1, 2012 and can be downloaded from
the product's home page (Microsoft Website).
The source code of Visual Studio 2012 consists of approximately 50 million lines of code.
The completion of final build of Visual Studio 2012 was announced on August 1, 2012 with
official launch event took place on September 12, 2012.

1.4 .NET framework

The Microsoft .NET Framework is a software framework that can be installed on computers
running Microsoft Windows operating systems.

.NET framework provides an environment for building, deploying and running web services
and other applications, .Net framework is one of the tools provided by the .NET infrastructure
and tools component of the .NET platform, .NET platform provides a new environment for
creating and running robust, scalable and distributed applications over the web. Here is the
picture to explain .NET framework:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
6

.NET framework shows that a programmer can write a program in any language that will be
translated into MSIL and then CLR will convert it to the native language from where we can
get the output of the program.

.NET Framework consists of three technologies:

1. Common Language runtime(CLR)


2. Framework Base Classes
3. User Interfaces ( ASP.NET, Windows forms, console Application)

1.5 Common Language Runtime (CLR) is the back bone for the .NET Framework, it is
responsible for loading and running C# programs, Base classes provide basic data types,
collection classes and other general classes for use by C# and other .NET Languages. It
support cross language interoperability.

Services of CLR:

✓ Loading and execution of program


✓ Memory isolation for applications
✓ Verification of type safe
✓ Compilation of IL(Intermediate language) to native executable code
✓ Providing meta data
✓ Automatic garbage collection (Memory Management)
✓ Enforcement of security
✓ Interoperability with other systems
✓ Managing exception and errors
✓ Debugging and profiling

Components of CLR

➢ Common Type System (CTS): it support variety of types and operations


found in most programming languages and therefore one language from other
does not require type conversions. Because of CTS we are able to develop
application in .NET in multiple languages like C#, VC++ and VB.
➢ Common Language specification (CLS): it’s the subset of CTS and therefore
the languages supporting the CLS can use each other’s class libraries as if they
are their own. The CLS defines the set of rules that enables interoperability on
the .NET platform.
➢ Microsoft intermediate language (MSIL or IL): is an instruction set into
which all the .NET programs compiled. It contains instructions for loading,
storing, initializing and calling methods, when we compile a program written in a
CLS-compliant language, the source code is complied into M IL.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
7

1.6 Framework Base Classes: .NET supplies a library of base classes that we can use to
implement application quickly. We can use them by inheriting in the program or by creating
object and calling their methods. By using System namespace in the programs we can use
most the functionality including:

✓ Input Output operation


✓ String handling
✓ Managing array, list, maps, etc
✓ Accessing files and file system
✓ Accessing the registry
✓ Security
✓ Windowing
✓ Database Management
✓ Evaluation of mathematical function
✓ Drawing
✓ Managing errors and exceptions
✓ Connecting to the internet
✓ And many more

User and Program Interface:

.NET framework allows us to implement following types of application for user and program
interfaces:

✓ Console Application
✓ Windows Application
✓ Web Application

In this book we will be covering first two applications with some real time examples.

Managed Code: As we know that the CLR is responsible for managing the execution of code
compiled for the .NET platform. The code that satisfies the CLR at run time in order to
execute is referred to as managed code. Compilers that are compatible to the .NET platform
generate managed code. C# compiler generates managed code (Intermediate language) and
then converted to native machine code by JIT compiler.

C# source code Compiler Managed Code or IL

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
8

Managed Code JIT Compiler Native Machine Code

Flow chart of CLR activities for executing a program:

C# Program

Compiler

IL and Metadata Metadata Engine

Linker Other Native Code

EXE Code

Class Loader Basic Class Library

Verifier Test

JIT Compiler

Native Machine Code

Runtime Manager

Output

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
9

Chapter #2: Introduction to C#

2.1 Introduction to C#

C# is a fully object oriented programming language developed by Microsoft Corporation. It


is a simple, efficient, productive and type-safe language derived from C, C++ and Java
languages.
It has been designed to support the key features of .NET Framework, the new
development platform of Microsoft for building component based software solution.
On .Net Framework C# can be used to develop console application, windows
application, Web application and other applications. Officially, Microsoft describes C# as a
“Simple, modern, object-oriented, and type-safe programming language derived from C
and C++” Most independent observers would probably change that to “derived from C,
C++ and Java”.
Syntactically, C# is very similar to both C++ and java, to such an extent that many
keywords are the same, and C# also shares the same block structure with braces( { } ) to
mark blocks of code, and semicolons to separate statements.

C#

ANSI C++ 2000

Java
1996
ANSI C 1995

C++ 1987

C
1983

1972

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
10

2. 2 C# Features:

1. C# is a fully object-oriented programming language; it


supports interface implementation, virtual functions and operating system.
2. A consistence and well-defined set of basic types.
3. Built in support for automatic generation of XML
documentation.
4. Automatic clean up of dynamically allocated memory.
5. Full access to the .Net base class library, as well as easy
access to the Windows API.
6. Pointers and direct memory access are available if required,
but the language is designed in such a way that we can work without them in almost
all case.
7. Support for properties and events in the style of Visual Basic.
8. C# supports delegates.
9. C# can be used to write Console and windows application.
10. C# can be used to write ASP.Net dynamic Web Pages and
XML Services.

2.3 Data Types:

There are two categories of predefined Data Types


i. Value types: it stores value directly.
ii. Referenced types: it stores a reference to the value.

CTS type:The basic predefined types recognized by C# are not intrinsic to the
language but are part of the .NET framework.
For example, when we declare an int in C#, what we are
actually declared is an instance of a .NET struct, System.Int32. this may sound like a
small point, but it has a profound significance, it meanse that we are able to treat all
the primitive data types syntactically as if they were classes that support certain
methods.
For examples, to convert an int i to a string:
string s=i.ToString( );

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
11

Predifined value types:


The built-in value types represent primitives, such as integer, floating point, character
and Boolean types.

Integer Types:
Name CTS Type Description

sbyte System.SByte 8-bit Signed int

short System.Int16 16-bit Signed int

int System.Int32 32-bit Signed int

long System.Int64 64-bit Signed int

byte System.Byte 8-bit unsigned int

ushort System.UInt16 16-bit unsigned int

uint System.UInt32 32-bit unsigned int

ulong System.UInt64 64-bit unsigned int

Floating point types:


Name CTS Type Description

float System.Single 32-bit Single precision

Double System.Double 64-bit double precision

Decimal Type:
Name CTS Type Description

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
12

decimal System.Decimal 128-bit high precision decimal notation

Boolean Type:
Name CTS Type Description

bool System.Boolean True / False

Chracter Type:
Name CTS Type Description

char System.Char 16-bit(Unicode) character

Predefined reference Type:


Name CTS Type Description

object System.Object The root type, all other types in the


CTS are derived

string System.String Unicode characters string

A sample console application program in C#:


using System;
namespace ConsoleApp1
{
class Class1
{
public static void Main( )
{
string name="Rahul";
int a=10,b=20,c=30;
Console.WriteLine("Hi "+name);
Console.WriteLine("Integer values are {0}, {1}, {2} ",a, b, c);
Console.ReadLine();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
13

}
}

Output:

Hi Rahul
Integer values are 10, 20, 30

Program description:

Using : using is the keyword to import the namespace in the program.

System: System is the root namespace of C# having all the inbuilt classes and interfaces.
it just like the package in java.

Namespace: namespace is the way to organize related classes and other types, unlike a
file of a component; namespace is a logical, rather than a physical grouping. When we
define a class in a C# file, we can include it within a namespace definition. Later, when we
define another class that performs related work in another file, we can include it within the
same namespace. It is just like project name in visual basic. By default C# project name is
the namespace of the program. Here consoleAppl1 is the console application project
name.

Class Sample: sample is just the user defined class having the main method.

Public: is the access specifier which helps the function to be accessed from outside the
namespace.

Static: keyword allows the function to be called without creating the object of the class.

Void: is just a null data type specifying here that main is not returning anything from it.

Main: Main is the main method it must be starting with capital M.

String is an inbuilt reference type of data type, can be used to declare variable for
keeping string in it.

Executing C# program:

• Press F6 or click on build solution from the build menu.


• Press F5 key or Press the green button from the tool bar or
click on the start debugging from debug menu.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
14

2.4 MaxValue and MinValue

Numerical types of .NET support MaxValue and MinValue properties that provide
information regarding the range a given type can store. Here is an example showing
additional members.

using System;
namespace MyConsoleapplication
{
class maxminkey
{
static int Main(string[] args)
{
Console.WriteLine();
Show_Data_Functionality();
Console.ReadLine();
return -1;
}
static void Show_Data_Functionality()
{
Console.WriteLine("Data Type Functionality:");
Console.WriteLine("Max of int: {0}", int.MaxValue);
Console.WriteLine("Min of int: {0}", int.MinValue);
Console.WriteLine("Max of double: {0}", double.MaxValue);
Console.WriteLine("Min of double: {0}", double.MinValue);
Console.WriteLine("double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("double.NegativeInfinity: {0}", double.NegativeInfinity);
Console.WriteLine("bool.FalseString: {0}", bool.FalseString);
Console.WriteLine("bool.TrueString: {0}", bool.TrueString);

Console.WriteLine();
}
}
}

The output is:

Data Type Functionality:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
15

Max of int: 2147483647


Min of int: -2147483648
Max of double: 1.79769313486232E+308
Min of double: -1.79769313486232E+308
double.Epsilon: 4.94065645841247E-324
double.PositiveInfinity: Infinity
double.NegativeInfinity: -Infinity
bool.FalseString: False
bool.TrueString: True

2.5 Enumerations:
An enumeration is a user-defined integer type. When we declare an enumeration, we specify
a set of acceptable values that instances of that enumeration can contain. Not only that, but
we can give the value user-friendly names. C++ does support enumerations (or enums ), but
C# enumerations are far more powerful than their C++ counterparts.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Enumtest
{
// enumeration definition
public enum timeofday
{
morning = 0, afternoon = 1, evening = 2
}
static void Main(string[] args)
{
greeting(timeofday.morning);
Console.ReadLine();
}
public static void greeting(timeofday td)
{
switch(td)
{
case timeofday.morning: Console.WriteLine("Good Morning");
break;
case timeofday.afternoon: Console.WriteLine("Good afternoon");
break;
case timeofday.evening: Console.WriteLine("Good Evening");
break;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
16

}
}

}
}

Output: Good Morning

2.6 Flow Controls

Flow controls are same in C# as in C/C++.

Here we are just discussing the syntax/simple example of the flow controls, later in
console application unit all these controls will be used with real examples.

1. Conditional statement
If statement: is used to check one or more condition.
Syntax:
If (condition)
Statment1;
Else
Statemaent 2;

Example:
If(a>b)
Console.writeLine(“a is greater that b”);
else
Console.writeLine(“a is not greater than b”);

Switch Statement: is used to select one case out of many.


Example:
switch(val)
{
case 1: Console.writeLine(“value=1”);
break;
case 2: Console.writeLine(“value=2”);
break;
case 3: Console.writeLine(“value=3”);
break;
case 4: Console.writeLine(“value=4”);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
17

break ;
default:
Console.writeLine(“value not from the cases”);
break;
}

2. Looping statement

For loop
Example:
int 1;
for(i=1;i<=100;i++)
{
Console.writeLine(“i=”+i);
}

While loop
Example:
int i=1;
While(i<=100)
{
Console.writeLine(“i=”+i);
I++;
}

Do-while loop: do-while loop is the only exit control loop, rest all are entry control.
Example:
Int i=20;
do{
Console.writeLine(“i=”+i);
i--;
}while(i>0);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
18

Foreach statement: The foreach statement is similar to for loop but implemented
differently. It enables us to iterate the element in array and collection classes such as
List and HashTable.
Syntax:
foreach(type variable in expression)
{
Body of the loop;
}

Example:
Program for printing an array values using foreach loop:

Using System;
Class Test1
{
public static void Main( )
{
int [ ] list={1,2,3,4,5,6,7,8,};
foreach(int n in list)
{
Console.writeLine(“List=”+n);
}
Console.readLine(); // to hold the output
}
}
Here console.readLine() wait for the key press or input, but input is not assigned in any
variable. Finally it will hold the output of the program till we are not pressing any key, in
C/C++ getch() function is used for the same purpose.

3. Jump statement
Goto statement: goto statement was removed from java but introduce here in C# like
C/C++, which help to jump from one statement to another statement.
Example:

Using System;
Class Test2
{
public static void Main( )

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
19

{
int i=1;
Show:
Console.writeLine(“value “+i)
i++;
if(i<10)
goto Show;
Console.writeLine();
}
}

Continue and break Statement:


Break statement can be used to break the loop or conditional statement, while
continue statement can be used to continue the loop skipping some part of the loop.
Examples:

Using System;
Class Test3
{
Public static void Main( )
{
int i=1;
While(i<=100)
{
Console.writeLine(“i=”+i);
i++;
If(i==51)

Break;

}
}

Using System;
class Test4
{
public static int Main( )
{
for(int i=1;i<=50;i++)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
20

{
Console.writeLine(“i=”+i);
if(i<20)
continue;
Console.writeLine(“<20”);
}
Console.readLine();
return 0;
}
}

2.7 Operators:

All the operators in C# are same as in C/C++, here all types of operators are:

1. Arithmetic operator
Example: + - * / %
2. Relational operator
Example: < <= > >= ==
!=
3. Logical operator
Example: && || ! & | ^
4. Assignment operator
Example: =
5. Increment and decrement operator
Example: ++ --
6. Conditional operator
Example: ?:
7. Bitwise operator
Example: & | ^ ~ << >>
8. Special operator
Example: is as typeof sizeof new .(dot)
checked unchecked

2.8 Adding Comments in C# Program:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
21

Comment statements are same as in C++, it uses both the single and multiple Line
comments statement.

Single Line comment:

// this is the single Line comment statement.

Multi-Line Comment:

/* This is the multiple line comment

That means multiple lines of the program can be commented by it.

*/

2.9 Type Casting: Converting data from one type to another type, especially from big size to
small size variable.

Implicit type conversion: implicit type casting is done without losing any data, it as an
automatic type conversion from a small variable to a big variable

Example:

short s=15;
int n=s; //conversion from short to int
long x=n; //conversion from int to long
Explicit type casting: value from a big size variable cannot be assigned to a smaller size
variable implicitly, here we can use explicit conversion but it may result in loss of data.

Example:

int n=50;
byte b=(byte)n; //Casting from int to byte
float f=120.01f;
int y=(int)f; //Casting from float to int

Boxing and Unboxing

Boxing is the conversion of a value type (int, long, float, …….) to an object type, we need to
convert because from a value type variable we cannot call any method according to oops.

Example:

int n=100;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
22

object m=n; // Boxing

OR

object obj=(object)n; //Boxing using C-style casting

Unboxing is converting back from object to the value type:

Example:

int n=100;

object m=n; // Boxing

int x=(int)m; //Unboxing

In boxing operation, values of the variable and object are independent of each other; object
value resides on heap, while value type variable values resides on stack.

2.10 Command-Line Arguments

Let's look at the incoming array of string data. Now we want to update our application to
process any possible command-line parameters using a C# for loop.

//Program4.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mycommandline
{
class Program4
{
static int Main(string[] args)
{

Console.WriteLine("Command Line Arguments");


Console.WriteLine();
for(int i = 0; i < args.Length; i++)
Console.WriteLine("Arg: {0}", args[i]);
Console.ReadLine();
return -1;
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
23

Here, we are checking to see whether the array of strings contains the number of items
using the Length property of System.Array.

C:\>cd CSharp

C:\CSharp>csc Program4.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

C:\CSharp>Program4 argA argB argC

Command Line Arguments


Arg: argA
Arg: argB
Arg: argC

C:\CSharp>

As we loop over each item in the array, its value is printed to the console window.

We can use an alternative to the standard for loop. We may iterate over an incoming string
array using the C# foreach keyword:

foreach(string a in args)
Console.WriteLine("Arg: {0}", a);

We are also able to access command-line argument using the static


GetCommandLineArgs() method of the System.Environment type. The return value of this
method is an array of strings. The first index identifies the name of the application itself,
while the remaining elements in the array contain the individual command-line arguments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyFirstCSharpCode
{
class Program5
{
static int Main(string[] args)
{

Console.WriteLine();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
24

string[] arguments = Environment.GetCommandLineArgs();


foreach(string arg in arguments)
Console.WriteLine("Arg: {0}", arg);
Console.ReadLine();
return -1;
}
}
}

Output is

C:\CSharp>csc Program5.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.

C:\CSharp>Program5 argA argB argC

Arg: Program5
Arg: argA
Arg: argB
Arg: argC

C:\CSharp>

Command-Line Arguments from window

While in the real world, the user supplies the command-line arguments, we may want to
specify command-line argument during the development cycle.

To specify the arguments with Visual Studio 2010, double-click the Properties icon from
Solution Explorer.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
25

Then, select the Debug tab on the left side. After that we can specify values using the
Command line arguments text box.

2.11 System .Environment Class

System.Environment Class: The Environment class allows us to obtain a number of details related
to the operating system via various static members.

Here is our new code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyConsoleApp
{
class Program

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
26

{
static int Main(string[] args)
{
Console.WriteLine("System.Environment Class");
Console.WriteLine();
ShowEnvDetails();
Console.ReadLine();
return -1;
}
static void ShowEnvDetails()
{
foreach (string drv in Environment.GetLogicalDrives())
Console.WriteLine("Drive: {0}", drv);
Console.WriteLine("OS: {0}", Environment.OSVersion);
Console.WriteLine("# of processors: {0}",
Environment.ProcessorCount);
Console.WriteLine(".NET Version: {0}", Environment.Version);
}
}
}

The output is:

System.Environment Class
Drive: C:\
Drive: D:\
Drive: E:\
Drive: F:\
Drive: Y:\
Drive: Z:\
OS: Microsoft Windows NT 6.0.6001 Service Pack 1
# of processors: 2
.NET Version: 4.0.30319.1

2.12 Structure

A Structure is one of the ways to modularize the program, a C# structure can hold data and
member functions as well like a class. It is a familiar and convenient way to encapsulate
different variables and the methods in a structure. But it cannot be inherited like a class.

Structure is a value type which is stored at the stack, while a class is a reference type which
is stored at the heap data structure.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
27

A structure’s variable can be created like any other variables of value types, and value can be
assigned using (dot) operator.

Syntax without method


struct struct_Name
{
Datatype var1;
Datatype var2;
-------------------
}
struct_Name A;
A.var1=value1;
A.var2=value2

Syntax with method


struct struct_Name
{
Datatype var1;
Datatype var2;
-------------------
Accessspecifier returntype Method1( )
{
--------------------------------------
}
Accessspecifier returntype Method2( )
{
--------------------------------------
}
}

C# program using structure to accept and show the detail of an item

using System;
namespace ConsoleApplication4
{
struct Item
{
public int sno;
public string name;
public float price;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
28

}
class struct1
{
public static void Main()
{
Item pen;
Console.WriteLine("Enter sno, name and price:");
pen.sno = int.Parse(Console.ReadLine());
pen.name = Console.ReadLine();
pen.price = int.Parse(Console.ReadLine());
Console.WriteLine("________Items Detail_____________");
Console.WriteLine("SNo =" + pen.sno);
Console.WriteLine("Name =" + pen.name);
Console.WriteLine("Price =" + pen.price);
Console.ReadLine();
}
}
}

C# program to demonstrate a Structure with constructor and methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
struct Item2
{
int sno;
string name;
float price;
public Item2(int s,string nm,int p) //constructor
{
sno = s; name = nm; price = p;
}
public void accept()
{
Console.WriteLine("Enter sno, name and price:");
sno = int.Parse(Console.ReadLine());
name = Console.ReadLine();
price = int.Parse(Console.ReadLine());
}
public void show()
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
29

Console.WriteLine("__________Items Detail______");
Console.WriteLine("SNo =" + sno);
Console.WriteLine("Name =" +name);
Console.WriteLine("Price =" +price);
}
}
class structTest
{
public static void Main()
{
Item2 pen=new Item2();
pen.accept();
pen.show();
Console.ReadLine();
}
}
}
Object of a structure with method must be created by new operator, it calls the constructor.
Item2 pen=new Item2();
Methods of a structure can be called similar to a class method.
pen.show();
Chapter #3: Arrays, Methods and string

3.1 Array

Array is a linear data structure, which allows us to store data of the same type in a sequential
manner. In C# array can be created using new operator dynamically. Like java, in C# also
array can be created of three types:

1. Single dimensional array


2. Multi dimensional array
3. Variable size array or Jagged Array

Creation of an array involves three steps:

1. Declaring the array: Declaring array name, dimension and type.


Example:
int [ ] List; //single dimensional
float [ ] list1;
Int[ , ] matrix; //multi dimensional
2. Creation of array: Giving the size to the array.
Example: List= new int[size];
List=new int[5];

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
30

matrix=new int [no-of-rows, no-of-cols];


matrix=new int[3,4];
3. Initializing of array: Assigning the values to the array.
Example:
Single Dimensional Array
List[0]=111;
List[1]=112;
………………
List[size-1]=120;

Two/Multi Dimensional Array


matrix[0,0]=1;
matrix[0,1]=2;
matrix[1,0]=3;

Program to sort a list of N size:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void Main( )
{
int n,i,j,temp;
int[] list;
Console.WriteLine("Enter the size of an array");
n=int.Parse(Console.ReadLine());
list = new int[n];
Console.WriteLine("Enter " + n + " Elements");
for (i = 0; i < n; i++)
{
list[i] = int.Parse(Console.ReadLine());
}
// Sorting process
for (i = 0; i < n - 1; i++)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
31

{
for (j = i + 1; j < n; j++)
{
if (list[j] < list[i])
{
temp = list[j];
list[j] = list[i];
list[i] = temp;
}
}
}
//printing the array's elements
for (i = 0; i < n; i++)
{
Console.WriteLine("list[" + i + "]=" + list[i]);
}
Console.ReadLine();
}
}
}

Program to accept and print a M x N matrix.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Class2
{
public static void Main()
{
int m,n, i, j;
int[,] matrix;
Console.WriteLine("Enter the number of rows");
m = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the numer of columns");
n = int.Parse(Console.ReadLine());

matrix= new int[m,n];

Console.WriteLine("Enter " + m +"x"+n+ " Elements of the matrix");


for (i = 0; i < m; i++)
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
32

for (j = 0; j < n; j++)


{
matrix[i,j] = int.Parse(Console.ReadLine());
}
}
// printing the matrix
Console.WriteLine("Your Matrix");
for (i = 0; i < m ; i++)
{
for (j = 0; j < n; j++)
{
Console.Write(" " + matrix[i, j]);
}
Console.WriteLine();
}

Console.ReadLine();
}

}
}

3.1.1 Creating variable size or jagged array:

Int [ ][ ] vmat = new int[4][ ]; //creating 4 rows but no columns


Vmat[0]=new int[3]; //creating space for 3 number at first row.
Vmat[1]=new int[2]; //creating space for 2 number at second row.
Vmat[2]=new int[3];
Vmat[3]=new int[4];

Virtual memory location can be of the vmat array.


0 1 2 3
0

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
33

3.1.2 The methods of the System.Array class: In C#, every array we create is
automatically derived from the System.Array class. This class defines a number of methods
and properties that can be used to manipulate arrays more efficiently.
We can call these methods from array name just with the help of dot operator.
Example:
int [ ] list = new int[5];
int m=list.Max( );
Methods Description

CopyTo( ) Copy elements from one array to another


array.

GetLength( ) Returns the number of elements from the


array

GetValue( ) Returns the value from a given index of


the array

SetValue( ) Sets the value at the given index

GetUpperBound( Returns the upper index of the array


)

Min( ) Returns the Min value from the List/Array

Max( ) Returns the max value from the list

Sum( ) Returns the sum of the values of the list

Count( ) Returns the length of the array

Property Description

Length Is a properties,Gives the length of an


array

Program to use some of the methods and property of System.Array class:

using System;
using System.Collections.Generic;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
34

using System.Linq;
using System.Text;

namespace ConsoleApp3
{
class arraymethods
{
public static void Main()
{
int n, i, j;
int[] list;
Console.WriteLine("Enter the size of an array");
n = int.Parse(Console.ReadLine());
list = new int[n];
Console.WriteLine("Enter " + n + " Elements");
for (i = 0; i < n; i++)
{
list[i] = int.Parse(Console.ReadLine());
}

//printing the array's elements


for (i = 0; i < n; i++)
{
Console.WriteLine("list[" + i + "]=" + list[i]);
}

// counting number of cells


j = list.Count();
Console.WriteLine("Array Size=" + j);

//getting length of the array


j = (int)list.LongLength;
Console.WriteLine("No of elements in array=" + j);

//setting elements at 3rd position(index no. 2)


list.SetValue(111, 2);

//getting value from 3rd position


object ob = list.GetValue(2);
Console.WriteLine("Element at 3rd position=" + ob);

//getting sum of the list elements


j=list.Sum();
Console.WriteLine("Sum of the list elements=" + j);

//length property to get the length of the list

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
35

j=list.Length;
Console.WriteLine("Length of the list=" + j);

//getting the data type of the array(list)


Console.WriteLine("Type of the list=" + list.GetType());

//getting the upper bound /upper index of the list


Console.WriteLine("Upper bound of the list="+ list.GetUpperBound(0));

//getting the min value of the list


Console.WriteLine("Minimum value of the list=" + list.Min());

//geting the max value of the list


Console.WriteLine("Getting the max value of the list=" + list.Max());

Console.ReadLine();
}

}
}

3.2 ArrayList

ArrayList class: ArrayList is a class of System.Collections namespace that can store a


dynamically sized array of objects. It defines number of methods and properties to deal with
the operations like sorting, removing, enumerating its contents, count etc.
Syntax to create an ArrayList object:

ArrayList object-name = new ArrayList( );


ArrayList object-name= new ArrayList(N);

Here we are creating an object of N size; but if we want to put more that N elements to the list
we can do it, because arraylist expands its size according to the use, that we will see in the
following program. And if we don’t give the size, by default it creates the object with 16 sizes.

Assigning the value to the ArrayList object:


We can assign any types of values to the object, it’s just like the vector in java, and it keeps a
value as an object.
Example:
ArrayList alist= new ArrayList( );

alist.add(“Bangalore”);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
36

alist.add(“2012”);
OR
alist.add(Console.ReadLine() ); // accepting data from keyboard

Following is the list of methods and properties of ArrayList class:


Methods/Properties Description
Add( ) Adds an object to the list at the end
Clear( ) Delete all elements from the list
Contains( ) Determines if an elements is in the list
CopyTo( ) Copies a list to other list
Insert( ) Inserts an element to the list at specified position
Remove( ) Remove first occurrence of an elements from the list
RemoveAt( ) Remove the element form the specified place
RemoveRange( ) Remove a range of elements from the list
Sort( ) Sort the array/list
Reverse( ) Method to reverse the list values/elements
Capacity is a property to get or set the capacity of elements in the list
Count is a property to get the actual number of elements present
in the list.

Program to use ArrayList with some methods and properties:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace arraylisttest
{
class Testarraylist
{
public static void Main()
{
ArrayList al = new ArrayList(5);
Console.WriteLine("Enter 10 numbers");
for (int i = 0; i < 10; i++)
{
al.Add(Console.ReadLine());

}
//sorting the elements of the list
al.Sort();
Console.WriteLine("Elements in sorted order");

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
37

for (int i = 0; i < al.Count; i++)


Console.WriteLine(al[i]);

//Reversing the contents of the arraylist using inbuilt method


al.Reverse();
Console.WriteLine("Elements in reverse order");
for (int i = 0; i < 10; i++)
Console.WriteLine(al[i]);

//adding one extra value to the arraylist


al.Add("2000");
Console.WriteLine("List capacity="+ al.Capacity);
Console.WriteLine("Data type of the List :" + al.GetType());

Console.WriteLine("Total elements in the List=" + al.Count);


//inserting an object 100 at 3rd position in the list
al.Insert(3,100);

//getting the index of the element "extra".


Console.WriteLine("Index of the value 2000="+al.IndexOf("2000"));

Console.WriteLine("Elements at the end");


for (int i = 0; i < al.Count; i++)
Console.WriteLine(al[i]);
Console.WriteLine("Total elments in the list=" + al.Count);
Console.ReadLine();

}
}

Output:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
38

3.3 User defined function / Methods

Methods can be implemented within the scope of classes or structures and prototyped within
interface types. Methods may be written with various keywords (internal, virtual, public,
private, protected, new, static ) to qualify their behavior.

While the definition of a method in C# is straightforward, there are a handful of keywords that
we can use to control how arguments are passed to the method.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
39

If a parameter is not marked with a parameter modifier, it is assumed to be passed


(None)
by value, meaning the called method receives a copy of the original data.

Output parameters must be assigned by the method being called (and therefore are
out passed be reference). If the called method fails to assign output parameters, we
are issued a compiler error.

The value is initially assigned by the caller and may be optionally reassigned by the
ref called method (as the data is also passed by reference). No compiler error is
generated if the called method fails to assign a ref parameter.

This parameter modifier allows us to send in a variable number of arguments as a


params single logical parameter. A method can have only a single params modifier, and it
must be the final parameter of the method.

Default Parameter-Passing (None)

The default manner in which a parameter is sent into a function is by value. In other words, if
we do not mark an argument with a parameter-centric modifier, a copy of the data is passed
into the function. Exactly what is copied will depend on whether the parameter is a value type
of a reference type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mymethods
{
class Program
{
static int add(int x, int y)
{
int ans = x + y;
x = 100; y = 200;
return ans;
}

static void Main(string[] args)


{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
40

int a = 10, b = 20;


Console.WriteLine("Before call add(): a = {0}, b = {1}", a, b);
Console.WriteLine("Ans = {0}", add(a, b));
Console.WriteLine("After call add(): a = {0}, b = {1}", a, b);
Console.ReadLine();
}
}
}

Output is:

Before call add(): a = 10, b = 20


Ans = 30
After call add(): a = 10, b = 20

Numerical data is value types. So, if we change the values of the parameters within the
scope of the member, the caller is unaware, given that we are changing the values on a copy
of the caller's data:

static int add(int x, int y)


{
...
x = 100; y = 200;
...
}

3.3.1 The out Modifier

In this section, we are dealing with output modifier. Methods that have been defined to take
output parameters (via the out keyword) are under obligation to assign them to an
appropriate value before exiting the method.

To demonstrate, here is an alternative version of the add() method that returns the sum of
two integers using the out modifier while the physical return value of this method is now void.

Example program with a method with out parameter


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mymethods
{
class Program
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
41

static void add(int x, int y, out int ans)


{
ans = x + y;
}

static void Main(string[] args)


{
int answer;
add(2010, 2011, out answer);
Console.WriteLine("2010 + 2011 = {0}", answer);
Console.ReadLine();
}
}
}

Output from the run is:

2010 + 2011 = 4021

Calling a method with output parameter also requires the use of the out modifier. Local
variables passed as output variables are not required to be assigned before use.

The example above is just for demonstration purpose, and actually we have no reason to
return the value of our summation using an output parameter. But the out modifier does
serve a very useful purpose: it allows the called to obtain multiple return values from a
single method invocation.

Example program with multiple out parameter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mymethods
{

class Program
{
static void GetMultipleValues(out int a, out string s, out bool b)
{
a = 2010;
s = "string as one of multiple return values";
b = true;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
42

static void Main(string[] args)


{
int i; string str; bool b;
GetMultipleValues(out i, out str, out b);
Console.WriteLine("Int is: {0}", i);
Console.WriteLine("String is: {0}", str);
Console.WriteLine("Boolean is: {0}", b);
Console.ReadLine();
}
}
}

Output is:

Int is: 2010


String is: string as one of multiple return values
Boolean is: True

Methods that define output parameters must assign the parameters to a valid value before
exiting the methods. So, the following method will result in a compiler error, as the integer
parameter has not been assigned within the method scope:

static void ThisIsCompilerError(out in myInt)


{
Console.WriteLine("Error: myInt not assigned");
}

3.3.2 The ref Modifier

Reference parameters are necessary when we want to allow a method to operate on various
data points declared in the caller's scope such as sorting or swapping routine. Here is the
distinction between output and reference parameters:

• Output parameters do not need to be initialized before they passed to the method. It's
because the method must assign output parameters before exiting.
• Reference parameters must be initialized before they are passed to the method. It's
because we are passing a reference to an existing variable. If we don't assign it to an
initial value, that would be the equivalent of operating on an unassigned local variable.

Let's look at the following example which uses ref keyword by way of a method that swaps
two strings:

Example program with pass by reference method

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
43

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mymethods
{
class Program
{
static void SwapStrings(ref string s1, ref string s2)
{
string temp = s1;
s1 = s2;
s2 = temp;
}

static void Main(string[] args)


{
string s1 = "Edsger";
string s2 = "Dijkstra";

Console.WriteLine("Before: {0} {1}", s1, s2);


SwapStrings(ref s1, ref s2);
Console.WriteLine("After: {0} {1}", s1, s2);
Console.ReadLine();
}
}
}

With the output:

Before: Edsger Dijkstra


After: Dijkstra Edsger

The caller has assigned an initial value to local string data, s1 and s2. Once the call to
SwapStrings() returns, s1 now contains the value Dijkstra while s2 holds the value Edsger.

3.3.3 The params Modifier

C# supports the use of parameter arrays. To understand the role of the params keyword,
we must understand how to manipulate C# arrays.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
44

The params keyword allows us to pass into a method a variable number of parameters of the
same type as a single logical parameter. Arguments marked with the params keyword can
be processed if the caller sends in a strongly typed array or a comma-delimited list of items.

Assume we wish to create a function that allows the called to pass in any number of
arguments and return the calculated average. If we were to prototype this method to take an
array of double, this would force the caller to first define the array, then fill the array and
finally pass it into the method. However, if we define Avarage() to take a params of integer
data types, the caller can simply pass a comma-delimited list of doubles. The .NET runtime
will automatically package the set of doubles into an array of type double behind the
scenes:

Example program with a method with multiple parameters

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mymethods
{
class Program
{
static double Average(params double[] values)
{
Console.WriteLine("{0} doubles", values.Length);

double sum = 0;
if (values.Length == 0)
return sum;
for (int i = 0; i < values.Length; i++)
sum += values[i];

return (sum / values.Length);


}

static void Main(string[] args)


{
double avg;
//passing 5 parameters
avg = Average(1.0,2, 3, 4,5.0);
Console.WriteLine("Average of data = {0}", avg);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
45

double[] data = { 82, 94, 72, 64, 97 };


//Passing 1 parameter
avg = Average(data);
Console.WriteLine("Average of data = {0}", avg);

//calling same function without arguments


Console.WriteLine("Average of data = {0}", Average());

Console.ReadLine();
}
}
}

Output is:

5 doubles
Average of data = 3
5 doubles
Average of data = 81.8
0 doubles
Average of data = 0

The method Average() has been defined to take a parameter array of doubles. What this
method is actually saying is "Send me any number of doubles and I'll calculate the
average." So, we can call the method in any of the ways shown above example.

3.4 String Handling

Here we are covering string in short to just test the string classes and its methods.

string is a class that is specifically designed to store a string and allow a large number of
operations on the string, also because of the importance of this data type, C# has its own
keyword and associated syntax to make it particularly easy to manipulate strings using this
class.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
46

Declaring and concatenating string using operator overloads.

string str = "New";


str = str + " Delhi";
str += " and Bangalore";
Console.WriteLine("string=" + str);

Methods and properties of the string Class:

CompareTo( ) compares the contents of two string

Concat( ) Concatenate two string Contains

CopyTo( ) Copy string to other string object

Equals( ) Checking the equality of two string

Split( ) splits the string into an array of substring, break occurs when a
given character occurs

ToLower( ) convert a string to lower case

ToUpper( ) Convert a string to upper case

Trim( ) delete the extra spaces from the string

IndexOf( ) Returns the index of specified character

Remove() remove sub string from a string

Replace() Replace the character with other character

SubString() method to cut substring

Length length is a property of string class, it returns the length

A sample String Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Class2
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
47

static void Main()


{
string s1="C#", s2=".NET Programming";
string s3=s1+s2;

Console.WriteLine("Concatinated string :" + s3);


Console.WriteLine("Upper case :" + s3.ToUpper());
if (s1.CompareTo(s2) == 0)
{
Console.WriteLine("Srings are equal");
}
else
Console.WriteLine("Srings are not equal");
Console.WriteLine("Length of string is :" + s3.Length);

Console.ReadLine();
}
}
}

Building Strings:

As we know string is a class that implements a large number of very useful methods.
However, the string class has a shortcoming that makes it very inefficient for making
repeated modification to a given string; StringBuilder class allows operations like appending,
inserting, replacing character or substring to a given string.

Methods and properties of StringBuilder class are:

Append( ), Clear( ), CopyTo( ), Equals( ), GetType( ), Insert( ), Remove( ), Replace( )

ToString( ), Capacity, Length, MaxCapacity

StringBuilder defines methods that allow us to replace or format segments. To use this type,
we need to import the proper namespace:

using System.Text;

When we call members of StringBuilder, we are directly modifying the object's internal
character data instead of obtaining a copy of the data in a modified format. When we create
an instance of the StringBuilder, we can supply the object's initial startup values via one of
many constructors. Let's look at the code which shows the usage of StringBuilder.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
48

As we see, we are appending to the internal buffer, and are able to replace (or remove)
characters. By default, a StringBuilder is only able to hold a string of 16 characters or less.
But this initial value can be changed via an additional constructor argument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstCSharpCode
{
class Programstr
{
static int Main(string[] args)
{
Console.WriteLine();
Show_StringBuilder_Functionality();
Console.ReadLine();
return -1;
}
static void Show_StringBuilder_Functionality()
{
StringBuilder sb = new StringBuilder("Simplicity, ");
sb.AppendLine(" Is the best policy, ");
sb.AppendLine("become simple!");
sb.Append("\n");
sb.AppendLine("C# Programmer");
Console.WriteLine(sb.ToString());
sb.Replace("!", ".");
Console.WriteLine(sb.ToString());
Console.WriteLine("SB has {0} chars.", sb.Length);
Console.WriteLine();
}
}
}

Chapter #4: Classes and Objects


4.1 Class

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
49

A class is a user-defined data type that is composed of members (member variables and
member functions) such as data, constructors, properties, methods, events, and so forth.
The set of field data represents the state of a class instance (object). By grouping data and
related functionality in a class definition, we are able to modul our program after entities in the
real world.

In .NET by default, all the classes will be under the namespace, the project name we give
during the staring of the application that project name will become the namespace; a
namespace is a collection of classes that means we can write many classes in the same
namespace.

Here all examples are given in console application but if we work with windows and web
application then also it will be the same, there each form or page represents a class.

Here is a sample class:

class student
{
public string name;
public int age;
public void Show( )
{
}
}

The member variables are declared using public access modifier. Public members of a class
are directly accessible once an object (instance of a given class) of this type has been
created.

using System;
namespace TestProject
{
class student
{
public string name;
public int age;
public void Show()
{
Console.WriteLine("{0}'s age is {1} Years.", name, age);
}

static void Main(string[ ] args)


{
Student st = new student ();
st.name = "Eklavya";
myToy.age = 22;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
50

st.Show();
Console.ReadLine( );
}
}
}

4.2 Allocating Object

Objects must be allocated into memory using the new keyword. If we don't use the new
keyword and attempt to use our class variable in a subsequent code, we'll get a compiler
error, something like “Use of unassigned local variable”:

static void Main(string[] args)


{
Student st;
st.name = "John"; //error
}

To correctly create a class type variable, we should define like that:

static void Main(string[] args)


{
Student st = new student ();
st.name = "John";
}

4.3 Class Constructor

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
51

A constructor is a special method of a class that is called directly when creating an object
using the new keyword. However, unlike a normal method, constructors never have a return
type (not even void and are always named identically to the class they are constructing.

Example:-

class student
{
public string name;
public int age;
public student( ) //constructor
{
name=”John”;
age=22;
}
}

Default Constructor

Every class is provided with a default constructor that we may redefine. A default
constructor never takes argument, by definition. Beyond allocating the new object into
memory, the default constructor ensures that all field data is set to an appropriate default
value. If we can not satisfied with these default assignments, we may redefine the default
constructor to meet our needs.

using System;
namespace TestProject
{
class student
{
public string name;
public int age;

public student() //Default Constructor


{
name = "xyz";
age = 0;
}

public void Show()


{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
52

Console.WriteLine("{0}'s age is {1} Years.", name, age);


}

static void Main(string[] args)


{
student st = new student();
st.Show();

Console.ReadLine();
}
}
}

Custom Constructor

In general, classes define additional constructors besides the default. We provide the object
user with a simple and consistent way to initialize the state of an object directly at the time of
creation. In the following example with three class constructors:

using System;

namespace TestProject
{
class student
{
public string name;
public int age;

public student()
{
name = "John";
age = 24;
}

public student(string n)
{
name = n;
}

public student (string n, int s)


{
name = n;
age = s;
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
53

public void Show()


{
Console.WriteLine("{0}'s age is {1} mph.", name, age);
}

static void Main(string[] args)


{
student st1= new student();
st1.Show( );
student st2= new student(“Sathish”);
st2.Show( );
student st3= new student(“Rozi”,20);
st3.Show( );

Console.ReadLine();
}
}
}

What makes one constructor different from another is the number of and type of constructor
arguments. So, the student class has overloaded the constructor to provide a number of
ways to create the object at the time of declaration.

4.4 The this Keyword

C# supports this keyword which provides access to the current class instance. One of uses
of this keyword is to resolve scope ambiguity, which can arise when an incoming parameter
is named identically to a data field of the type as shown in the following example:

class student
{
public string name;

public void Setdata(string name)


{
name = name;
}

The code will compile just fine, but the value of the name filed is an empty string. Instead the
code should be as follow:

class student

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
54

{
public string name;

public void Setdata(string name)


{
this.name = name;
}

If there is no ambiguity, we are not required to use this keyword when a class wants to
access its own data or members. For example, if we rename the string data member to
stud_name, the use of this is optional as there is no longer a scope of ambiguity:

class student
{
public string stud_name;

public void Setdata(string name)


{
stud_name = name;
}

4.5 The static Keyword

A C# class can define any number of static members using static keyword. The static
members can be invoked directly from the class level rather than a type instance.

Console obj;

If we write the code, we get an error message: Cannot declare a variable of static type
System.Console.

We cannot invoke the WriteLine() method from the object level, either.

Console obj = new Console();


obj.WriteLine("This is an error");

The right invocation of the method WriteLine() is:

Console.WriteLine("This is the correct use of WriteLine()");

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
55

Static members are items that are deemed to be so commonplace that there is no need to
create an instance of the type when invoking the member. While any class can define static
members, they are most commonly found within utility classes such as System.Console,
System.Math, System.Environment, or System.GC, and so on.

The static Methods

Let's see one example of static members, which are called from class name not from the
object.

Example :-

class Test
{
public static short n;
public static void show()
{
Console.WriteLine("Class variable's value");
Console.WriteLine("N=" + n);
}
}
Class staticTest
{
static void Main()
{
Test.n=5;
Test.show();
Console.ReadLine();

}
}

If we attempt to use nonstatic class data or call a nonstatic method of the class within a static
member's implementation, we'll get compile-time errors.

The static Data

Static data is just a variable declared with static keyword; it doesn’t take place in object like
other normal variables but will be shared by all the instances of the class.

Example: static short n;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
56

4.6 The static Constructor

A static constructor is a special constructor that is an ideal place to initialize the values of
static data when the value is now known at compile time such cases when we need to read in
the value from an external file or generate a random number, and so on. Here are a few
things related to the static constructors:

• A given class (or structure) may define only a single static constructor.
• A static constructor does not take an access modifier and cannot take any parameters.
• A static constructor executes exactly one time, regardless of how many objects of the
type are created.
• The runtime invokes the static constructor when it creates an instance of the class or
before accessing the first static member invoked by the caller.
• The static constructor executes before any instance-level constructors.

Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
class staticConst
{
static void Main()
{
ST obj1 = new ST();
ST obj2 = new ST();
ST obj3 = new ST();
obj1.show();
obj2.show();
ST.show2();
Console.ReadLine();

}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
57

class ST
{
static short n;
int m;
static ST() //access specifier not allowed with static constructor
{
Console.WriteLine("Constructor invoked");
n = 100;
}
public ST()
{ m = 101; }
public void show()
{
Console.WriteLine("N=" + n); //printing class value
Console.WriteLine("N=" + this.m); //printing object value
}
public static void show2()
{
Console.WriteLine("Class variable's value");
Console.WriteLine("N=" + n);
}
}

4.7 The static Classes

When a class has been defined as static, it is not creatable using the new keyword, and it
can contain only members or fields market with the static keyword.

The class that cannot be created does not appear all that useful. However, if we create a
class that contains nothing but static members and constant data, the class has no need to
be allocated in the first place. Let's take a look at the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticClass
{
static class TimeUtilClass
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
58

public static void PrintTime()


{
Console.WriteLine(DateTime.Now.ToShortTimeString());
}

public static void PrintDate()


{
Console.WriteLine(DateTime.Today.ToShortTimeString());
}

static void Main(string[] args)


{
TimeUtilClass.PrintDate();

// Compile error because we can't create static classes!


TimeUtilClass u = new TimeUtilClass();
}
}
}

Because this class has been defined with the static keyword, we cannot create an instance
of TimeUtilClass using the new keyword.

Prior to .NET 2.0, the only way to prevent the creation of a class type was to either redefine
the default constructor as private or mark the class as an abstract type using the abstract
keyword:

class TimeUtilClass
{
private TimeUtilClass(){}

public static void PrintTime()


{
Console.WriteLine(DateTime.Now.ToShortTimeString());
}

public static void PrintDate()


{
Console.WriteLine(DateTime.Today.ToShortTimeString());
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
59

abstract class TimeUtilClass


{
public static void PrintTime()
{
Console.WriteLine(DateTime.Now.ToShortTimeString());
}

public static void PrintDate()


{
Console.WriteLine(DateTime.Today.ToShortTimeString());
}
}

Though these constructs are still permissible, the use of static classes is a cleaner solution
and more type-safe, given that the previous two allowed nonstatic members to appear within
the class definition without error.

A project's application class which defines the Main() method is often defined as a static
class, to ensure it only contains static members and cannot be directly created:

static class Program


{
static void Main(string[] args)
{
...
}
}

4.8 Encapsulation Services

The idea of encapsulation is that an object's internal data should not be directly accessible
from an object instance. Rather, if the called wants to alter the state of an object, the user
does so indirectly using accessor (getter) and mutator (setter) methods. In C#, encapsulation
is enforced at the syntactic level using the public, private, internal, and protected
keywords. To demonstrate the need for encapsulation services, assume we have created the
following class definition:

class Book
{
public int Pages();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
60

The problem with public field data is that the item has no ability to intrinsically understand
whether the current value to which they are assigned is valid with regard to the current rule of
the system. As we know, the upper range of a C# int is quite large (2,147,483,647).
Therefore, the compiler allows the following assignment:

static void Main(string[] args)


{
Book pictureBook = new Book();
pictureBook.Pages = 1500000000;
}

Even though we don't have overflow error, it should be clear that a pictureBook with a
1,500,000,000 pages is unreasonable. If our system has rule that limits the number of pages
to 1000, we are at a loss to enforce this programmatically. Because of this, public field
typically have no place in a production-level class definition.

Encapsulation provides a way to preserve the integrity of an object's state data. Rather than
defining public fields, we should get in the habit of defining private data, which is indirectly
manipulated using one of two main techniques:

• Define a pair of accessor (getter) and mutator (setter) methods.


• Define a type property.

In addition to those, C# provides the readonly keyword, which also delivers a level of data
protection. Well-encapsulated class should hide the details of how it operates from the
outside. This is often referred as black box programming. The beauty of this approach is
that an object is free to change how a given method is implemented under the hood. It does
this without breaking any existing code making use of it, provided that the signature of the
method remains constant.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
61

4.9 Polymorphism: one name multiple form, it can be achieved in two ways:

Method overloading:
Method overloading is a process to define multiple methods with the same name in a class
with different number and different types of arguments.

Example-

class shapes
{
public double area(short r)
{
return 3.14 * r * r;
}
public int area(short l,short b)
{
return l*b;
}
public double area(float b,float h)
{
return 0.5*b*h;
}
public float area(float s)
{
return s * s;
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
62

A Program to demonstrate method overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
class poly
{

public static void Main()


{
short opt;
do
{
Console.WriteLine("------------Menu of the shapes-------------");
Console.WriteLine(" 1.Area of Circle");
Console.WriteLine(" 2.Area of Rectangle");
Console.WriteLine(" 3.Area of Triangle");
Console.WriteLine(" 4.Area of Square");
Console.WriteLine(" 5.Exit");
Console.WriteLine(" Enter your choice: ");
opt = short.Parse(Console.ReadLine());
shapes sh = new shapes();
switch (opt)
{
case 1: Console.WriteLine("Enter radius of the circle:");
short r = short.Parse(Console.ReadLine());
Console.WriteLine("Area of the circle= " + sh.area(r));
break;
case 2: Console.WriteLine("Enter sides ");
short x= short.Parse(Console.ReadLine());
short y = short.Parse(Console.ReadLine());
Console.WriteLine("Area of the Rectangle= " + sh.area(x,y));
break;
case 3: Console.WriteLine("Enter height and base ");
float h = short.Parse(Console.ReadLine());
float b = short.Parse(Console.ReadLine());
Console.WriteLine("Area of the Triangle= " + sh.area(h, b));
break;
case 4: Console.WriteLine("Enter a side ");
float s= short.Parse(Console.ReadLine());
Console.WriteLine("Area of the Square= " + sh.area(s));
break;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
63

case 5: Environment.Exit(0);
break;
default: Console.WriteLine("Invalid option ! Try again");
break;
}
} while (opt != 5);

}
}

class shapes
{
public double area(short r)
{
return 3.14 * r * r;
}
public int area(short l,short b)
{
return l*b;
}
public double area(float b,float h)
{
return 0.5*b*h;
}
public float area(float s)
{
return s * s;
}

}
}

4.10 Properties

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
64

Though we can encapsulate field data using traditional get and set methods, .NET prefers to
enforce data protection using properties. First of all, note that properties always map to
accessor and mutator methods in terms of CIL (Common Intermediate Language) code.
Thus, as a class designer, we're still able to perform any internal logic necessary before
making the value assignment.

Properties are the concept to set and get data of an object, its shortcut to accessor methods.
Example-

class Student
{
string name;
public string prop
{
set
{
name = value;
}

get
{
return name;
}
}
}
class prop1
{
static void Main(string[] args)
{
Student st = new Student();
st.prop = "Eklavya";

Console.WriteLine("Hello "+st.prop);
Console.ReadLine();
}
}

Output

Hello Eklavya

Indexers

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
65

Indexers are location indicators and are used to access class objects. Just like accessing
elements in an array. They are useful in cases is a container for other objects. An indexers
look like a properties and is written the same way as property is written. But with two
differences:

❖ The indexers take an index argument and look like an array.


❖ The indexers are declared using the name this.

The indexer is implemented through get and set accessor for the [ ] operator.

Example: Program to implement of an indexer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace indexerTest
{
class test
{
object[] obj = new object[5];
public object this[int index]
{
get{
if(index <0 && index >=obj.Count())
{
return null;
}
else
{
return (obj[index]);
}
}
set{
obj[index]=value;
}
}
}
class Program
{
static void Main(string[ ] args)
{
object[ ] list =new object[5];
list[0] = "26";
list[1] = "Jan";

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
66

list[2] = "2012";
foreach (object item in list)
Console.Write(" "+item);
Console.ReadLine();
}
}
}

Output: 26 Jan 2012

Chapter #5: Inheritance

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
67

5.1 Inheritance

Inheritance is one of the best features of object oriented programming (OOP), which allows
us to reuse the features of an existing class to a new class; it reduces the complexity and the
length of a program.

In other words, Inheritance is one of the pillars of OOP that facilitates code reuse.

Inheritance is of five types:

1. Single level inheritance

2. Multilevel inheritance

3. Hierarchical inheritance

4. Multiple inheritance

5. Hybrid inheritance

5.1.1: Single level inheritance: - in single level inheritance one class inherits another class.
Here the class which inherits called sub class or child class and the class which is inherited
by child called parent or base class.

Super/base/parent class
Class A

Class B
Sub/derived/child class

Syntax:

class A
{
------------
}
class B : A
{
------------
}

Example-

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
68

namespace ConsoleApplication
{
class single
{
static void Main()
{
B obj = new B();
obj.getab();
obj.show();
Console.ReadLine();
}
}
class A
{
public int a, b;
public void getab()
{
Console.WriteLine("Enter the value of a & b");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
}
}
class B : A
{
int c;
public B()
{
c = 100;
}
public void show()
{
Console.WriteLine("a=" + a);
Console.WriteLine("b=" + b);
Console.WriteLine("c=" + c);
}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
69

5.1.2: Multilevel Inheritance:- At least three classes required to implement multilevel


inheritance, a base class is inherited by a subclass and further subclass is inherited by
another sub class.

Syntax-

class A
{
------------
}
class B : A
{
------------
}
class C : B
{
------------
}

5.1.3: Hierarchical Inheritance:- One super class, many sub classes

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
70

Syntax-

class Item
{
------------
}
class Processor : Item
{
------------
}
class RAM : Item
{
------------
}

Example:-

A program to implement hierarchical inheritance

class Item
{
public int code;
public int price;
public string name;
public Item(int c, int p, string nm)
{
code = c;
price = p;
name = nm;
}
public void show()
{
Console.WriteLine("Code :" + code);
Console.WriteLine("Price :" + price);
Console.WriteLine("Name :" + name);
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
71

class Processor:Item
{
string model,speed;
public Processor(int c, int p, string nm, string mod,string spd) : base(c, p, nm)
{
model = mod;
speed=spd;
}
public void display()
{
show();
Console.WriteLine("Model :" + model);
Console.WriteLine("Speed :" + speed);
}
}

class RAM : Item


{
string size;
public RAM(int c, int p, string nm, string sz) : base(c, p, nm)
{
size=sz;
}
public void display()
{
show();
Console.WriteLine("Size :" + size);
}
}
class hierarchy
{
public static void Main()
{
Processor pro=new Processor(112,6000,"Intel Core","i5","3GH");
RAM ram=new RAM(113,4000,"DDR","4GB");
Console.WriteLine("----------Processor-----------");
pro.display();
Console.WriteLine("-------------RAM----------------");
ram.display();
Console.ReadLine();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
72

}
}

5.1.4: Multiple Inheritance: multiple inheritances cannot be achieved without interface;


graphically a multiple inheritance is opposite to hierarchical inheritance where multiple
interfaces and a class can be derived in a single class.

Implementation of interfaces

interface Addition
{
int add( );
}
interface Multiplication
{
int mult( );
}
class Computation : Addition , Multiplication
{
int x, y;
public Computation(int a, int b)
{
x=a; y=b;
}
public int add( )
{
retrun (x+y);
}
public int mult( )
{
return (x* y);
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
73

A Student Report program using Multiple Inheritance

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
74

5.1.5: Hybrid Inheritance: hybrid inheritance doesn’t have any specific picture, because a
hybrid inheritance can be achieved by using multiple types of inheritance, in general it is
rarely used.

Here we have two different shape but both of the same hybrid type.

Since we are using interface here in inheritance, we must discuss about it.

5.2 Interfaces:

An interface is similar to a class, but it provides a specification rather than an


implementation for its members. An interface is special in the following ways:

• A class can implement multiple interfaces. In contrast, a class can inherit from only a
single class.
• Interface members are all implicitly abstract. In contrast, a class can provide both
abstract members and concrete members with implementations.
• Structs can implement interfaces. In contrast a struct cannot inherit from a class.

public Interface Items


{
// Error! Interfaces cannot have fields.
public int qty;
// Error! Interface don't have constructors.
public Items() { qty = 0; }
// Error! Interface don't provide an implementation.
int Getqty() { return qty; }
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
75

Example of an Interface:-

interface Addition
{
int add( );
}

Extending interfaces
Ex1:
interface A
{
void show();
}
interface B:A
{
void display();
}
----------------------------------------------------------------------
Ex2:
interface A
{
---
}
interface B
{
---
}
interface C : A , B //multiple inheritance
{
---
}

Implementing Interface:
interface can be implemented in a class
Ex-
interface A
{
void show( );
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
76

class B : A
{

public void show( ) // implementing show( ) function


{
Console.WriteLine(“ I M Implemented in B”);
}
}

Now, here we can discuss some more topics related to inheritance.

5.3 Visibility Control:


in C# we have four types of accessibility modifiers which may be applied to classes and
members to specify their level of visibility.
These are:
1. public
2. private
3. protected
4. Internal

Class visibility is used to decide which parts of the system can create class objects.
A C# class can have one of two visibility modifiers public or internal, by default all class are
internal, that means the class can be accessible only from the same assembly.
But if you make a class public it can be accessible from outside assembly as well.
Class member’s visibility: class members can have any one of the five modifiers. When no
modifier is specified it defaults to private accessibility.
1. public
2. private
3. protected
4. internal
5. protected internal

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
77

Class member’s visibility

5.4 Overriding Methods:


as we know a method defined in super class is inherited by its subclass and is used by the
object of subclass, but if same methods with same argument are in both super and sub class
then there is problem at the time of method call. We can fix it by :
1. specify the method in super as virtual
2. specify the method in sub as override

when the method is called method defined in sub class is executed.


That means sub class method override super class method.

Here in this example, super and sub both the classes are having same named function
“Display”, to implement overriding in super class function is written with virtual keyword and in
sub class function is written with override keyword.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
78

Example to override a display method:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
79

5.5 Hiding method:


when we override a base class method, we declared the base class method as virtual and
sub class method with the keyword override. This resulted in “hiding” the base class method
from the subclass.

But if we have to hide base class method by sub class method without virtual, we can use
new operator with sub class method.

Ex-
class A
{
public void show()
{
Console.WriteLine(“A class”);
}
}
class B:A
{
public new void show()
{
Console.WriteLine(“Class B”);
}
}

5.6 Abstract Class:


Abstract class cannot be instantiated (object cannot be created). To use this class we must
inherit it.
Ex-
abstract class A
{
---------
---------
}
A obj=new A( ); //Error, object cannot be created of an abstract class.

Abstract Method:
it cannot have definition/implementation
it must be defined in non-abstract sub class
it can be declared only in abstract classes

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
80

Ex-
abstract class A
{
abstract void show( );
}

5.7 Sealed classes:


sealed classes cannot be inherited. If you have to prevent your class being further sub
classed for security reason, declare class with sealed keyword.
sealed class A
{
---
---
}
class B: A // Error, a sealed class cannot be inherited.
{
---
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
81

Chapter #6: Operator Overloading


6.1: Basic of operator overloading
Operator overloading is one of the key features of object-oriented programming (OOP). It
provides operators with special meaning for a data type. Operator meaning will be the same
but it will work on different data type which is not possible without it.
Example-
class A
{
int x;
float y;
}
A obj1=new A( );
A obj2=new A( );
A obj3=new A( );
obj3=obj1 + obj2; // adding two objects by overloading + operator.

obj1 obj2 obj3

Need for operator overloading


1. Mathematical or physical modeling where we use classes to represent objects such as
coordinates, vectors, matrices, complex number and so on.
2. Financial problem where a class represent an amount of money.
3. Text manipulation where classes are used to represent string and sentences.

6.2 Overloadable operators(which can be overloaded):


Binary arithmetic :- +, * , / , - , %
Unary arithmetic:- + , - , ++, --
Binary bitwise :- &, | , ^ , << , >>
Unary bitwise :- !, ~ , true , false
Logical operator : - == , != , >= , < , <= , >
Operators that cannot be overloaded:
Conditional operator:- && ,||
Compound statement:- +=, -=, *=, /=,
other operators:- [ ], ( ), =, ?:, ->, new,
sizeof, typeof, is , as

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
82

Defining operator overloading function.


Syntax-
public static returntype operator op( arg list)
{
method body / task defined
}
Example-
public static Test operator +( Test obj1, Test obj2)
{
Test obj3=new Test();
obj3.x=obj1.x + obj2.x;
obj3.y=obj1.y+obj2.y;
return obj3;
}

Here in this example operator + is a function which will be called automatically when we write
two objects with + operator to add, and it returns an object after addition that’s why the return
type is Test which is the class name.

6.3 A Program to overload binary operator, adding two complex numbers

class complex
{
double real, imag;
public complex()
{
real = 0.0;
imag = 0.0;
}
public void accept()
{
Console.WriteLine("Enter real part");
real = double.Parse(Console.ReadLine());
Console.WriteLine("Enter imaginarypart");
imag = float.Parse(Console.ReadLine());
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
83

public static complex operator +(complex c1, complex c2)


{
complex c3 = new complex();
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
public void display()
{
Console.Write("\t" + real);
Console.Write("+i" + imag);
Console.WriteLine();
}
}

class Program
{
static void Main(string[] args)
{
complex a, b, c;
a = new complex();
b = new complex();
c = new complex();
Console.WriteLine("Addition of 2 complex number using operator overloading");
Console.WriteLine("-------------------------------------------------------");
Console.WriteLine("First complex number");
a.accept();
Console.WriteLine("Second complex number");
b.accept();
c = a + b; //calling operator + function of complex class
Console.Clear();
Console.WriteLine("Sum of 2 complex numbers");
Console.Write("\t 1st complex number=");
a.display();
Console.Write("\t 2nd complex number=");
b.display();
Console.Write("sum=");
c.display();
Console.ReadLine();
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
84

6.4 A program to overload comparison operator

using System;

namespace ConsoleApplication4
{
class comparison
{
static void Main()
{
Time T1 = new Time(2, 30);
Time T2 = new Time(2, 30);
if (T1 == T2) //overloading comaparison operator ==
Console.WriteLine("Both are matching");
else
Console.WriteLine("Both are different");
Console.ReadLine();
}
}
class Time
{
short h, m;
public Time(short x, short y)
{
h = x;
m = y;
}
//definition of comparison operator == function
public static bool operator ==(Time t1, Time t2)
{
if (t1.h == t2.h && t1.m == t2.m)
return true;
else
return false;
}
public static bool operator !=(Time t1, Time t2)
{
if (t1.h != t2.h && t1.m != t2.m)
return false;
else
return true;
}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
85

When we overload comparison operator like ==, we need to overload its counterpart !=
operator as well, and also we need to define operator function with public static keywords.

6.5 A Program to overload unary operator

using System;

namespace ConsoleApplication4
{
class unaryop
{
public static void Main()
{
Complex c1 = new Complex(80,90);
Console.WriteLine("Complex number before operator overloading");
c1.show();
c1++; //Calling operator ++ function
Console.WriteLine("Complex number after operator overloading");
c1.show();
Console.ReadLine();

}
}
class Complex
{
double r, im;
public Complex(double x, double y)
{
r = x;
im = y;
}
public static Complex operator ++(Complex c) //overloading ++ operator
{
Complex T = new Complex(0,0);
T.r=++c.r;
T.im=++c.im;
return T;
}
public void show()
{
Console.WriteLine("Complex No ={0} +i {1}", r, im);
}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
86

After creating an object C1, C1++ statement looks like a very simple increment operation, but
it call the ++ function to add two complex number and increases both the elements real and
imaginary of a complex number.

Chapter #7: Delegate


7.1 Introduction to delegate:
Delegates are a special type of class that we can assign methods to. We can pass delegates
to methods and make them data members of a class. Delegates can have any number of
arguments as long as the delegate definition matches the signature of the method assigned
to it. Delegate’s object represents or acts for the methods of a class which are assigned to it,
that’s why it’s called delegate.
Delegate requires using an inbuilt Class System.Delegate. Generally in all object oriented
programming we can call the method of a class from the object of the same class or directly
“classname.method” if the method is static, but here we can call methods of a class from
delegate’s object which acts as same method.
Creating and using delegates involve four steps:
1. Delegate declaration
2. Delegate method declaration
3. Delegate instantiation
4. Delegate invocation
Example-
public delegate void mydelegate();
public void area( );
mydelegate op1=new mydelegate(classname.area);
op1( );
Here mydelegate is declared a delegate, area() suppose a method in a class, op1 is the
instantiation of the delegate object which is delegating for area method and at the end op1()
is the delegate invocation, that call area function. In simple, here op1 is the delegate of area
function.

To implement and understand better, see the examples below.

using System;
Namespace Myproject
{
delegate int arithop(int x,int y); //delegate declaration
class Mathop
{
public static int ADD(int x,int y) //delegate method Definition.
{
return x+y;
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
87

public static int SUB(int x, int y)


{
return x-y;
}
}

class DelTest
{
public static void Main( )
{
//delegate instantiation
Arithop op1=new Arithop(Mathop.ADD);
Arithop op2=new Arithop(Mathop.SUB);
//invoking delegate
Console.WriteLine(“Addition=“+ op1(10,20) );
Console.WriteLine(“Substration=“+ op2(100,20) );
Console.ReadLi ne();
}
}
}

A menu driven program to calculate area of different shapes using delegate

namespace ConsoleApplication1
{
delegate void printdelegate();
class dele
{
double length,breadth,height,base1,side,area;
public void rect()
{
Console.WriteLine("enter length");
length=Double.Parse(Console.ReadLine());
Console.WriteLine("enter breadth");
breadth=Double.Parse(Console.ReadLine());
area=length*breadth;
Console.WriteLine("area of rectangle="+area);
}
public void triangle()
{
Console.WriteLine("enter base");

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
88

base1=Double.Parse(Console.ReadLine());
Console.WriteLine("enter height");
height=Double.Parse(Console.ReadLine());
area=0.5*base1*height;
Console.WriteLine("area of triangle="+area);
}

public void square()


{
Console.WriteLine("enter side");
side=Double.Parse(Console.ReadLine());
area=side*side;
Console.WriteLine("area of square="+area);
}
}

class DeleTest
{
static void Main()
{
dele d = new dele();
int opt;
do
{
Console.Clear();
Console.WriteLine("ILLUSTRATION OF DELEGATES");
Console.WriteLine("1.Area of Triangle");
Console.WriteLine("2.Area of Rectangle");
Console.WriteLine("3.Area of Square");
Console.WriteLine("4.Exit");
Console.WriteLine("Enter your option:");
opt = int.Parse(Console.ReadLine());
printdelegate p;
switch (opt)
{
case 1: p = new printdelegate(d.triangle);
p();
Console.ReadLine();
break;
case 2: p = new printdelegate(d.rect);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
89

p();
Console.ReadLine();
break;
case 3: p = new printdelegate(d.square);
p();
Console.ReadLine();
break;

case 4: Environment.Exit(0);
break;
}
}
while (opt != 4);
}
}
}

7.2 Multicast Delegate

All delegate objects have natural ability to multicast. A delegate object can invoke multiple
methods, rather than a single method called multicast delegate, it is also known as
combinable delegates.

When we want to add multiple methods to a delegate object, we simply use overloaded +=
operator, rather than a direct assignment.

For example:

delegate void MultipleDelegate();


MultipleDelegate MD=new MultipleDelegate(calculate);
MD+=show;

Invoking MD will now call both Calculate and Show methods. Delegates are invoked in the
order they are added.

The - = method removes the right delegate operand from the left delegate operand. For
example:

MD -= Calculate;
Invoking MD will now cause only Show to be invoked.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
90

Calling += on a delegate variable with a null value works, and it is equivalent to assigning
the variable to a new value:

MultipleDelegate MD = null;
MD += show

If a multicast delegate has a non-void return type, the called receives the return value from
the last method to be invoked. The preceding methods are sill called, but their return value
are discarded. In most cases in which multicast delegates are used, they have void return
types, so this subtlety does not arise.

All delegate types implicitly inherit System.MulticastDelegate, which inherits from


System.Delegate. C# compilers += and -= operations made on a delegate to the static
Combine() and Remove() methods of the System.Delegate class.

Sample Program of a multiple Delegate:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Mdelegate
{
delegate void MulticastDelegate();
public static void Main()
{
MulticastDelegate MD=new MulticastDelegate(Maths.sum);
MD+= Maths.show;
MD();
Console.ReadLine();

}
}
class Maths
{
static int a,b,c;
public static void sum()
{
Console.WriteLine("Enter Two numbers");
a=int.Parse(Console.ReadLine());
b=int.Parse(Console.ReadLine());
c=a + b;
}
public static void show()

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
91

{
Console.WriteLine("{0} + {1} = {2}", a, b, c);
}
}
}

7.3 Event:

An Event is a delegate type class member that is used by the object or class to provide a
notification to other objects that an event has occurred. The client object can act on an event
by adding an event handler to the event.

Syntax to declare an event which requires declaring first delegate:

Access_modifier event Delegate_name Event_name;

Sample Event Program:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
public delegate void EventsDeligate(string str);
class Events
{
public static void Main()
{
EventsTest obj = new EventsTest();
EventsTest ET = new EventsTest();
ET.shoot+=new EventsDeligate(Ecatch);
ET.show();
Console.ReadLine();
}
static void Ecatch(string s)
{
Console.WriteLine("Event Message :"+s);
}
}
class EventsTest
{
public event EventsDeligate shoot;
public void show()
{
if (shoot != null)
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
92

shoot("Event triggred !");


}
}
}
}
Output: Event Message :Event triggered !

Chapter #8: Exception Handling


8.1 Managing Exceptions

An Exception is a run time error which occurs due to some condition like in an expression
where we divide a number by zero or try to access the array index which is out of
bound or trying to use a stack which is overflowing and so on. We cannot handle these
exceptions during compile time because it won’t be reported at that time, but will terminate
the execution and give error at the run time, we can handle these exceptions at the run time
by using try, catch and finally block, finally is optional. If the statement written in the try
block will be having any exception it will be thrown to catch where the exception type will be
stored in the object of the exception class.

Syntax to handle an exception:

try
{
Statement;
}
catch (Exception_class_name object)
{
Statement;
}

Example-

int a=10, b=0,c;

try
{
c = a / b;
}
catch (Exception e)
{
Console.WriteLine("Exception " + e);
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
93

We can write statements in the try block which are suspected to report exception, here c=a/b;
suspected to report divided by zero exception, try throws that exception to catch where it
stored in the object e of Exception type, which is printed from the catch block. Even if we do
not print the exception type, our exception will be managed and our program will not
terminate abnormally, to see the exception report we usually print the exception.

Since we may face many different types of exception, C# framework 4.0 specified around 52
inbuilt classes for all different exceptions in different scenario. Most of these classes are from
System namespace.

8.2 Some of the exceptions classes of .NET framework are:

Exception classes Description

Exception A generic exception, which handles all types of


exceptions.

NullReferenceException Occurs when you attempt to access the value of


an
object that doesn’t exist

ArgumentNullReferenceException Occurs when an unexpected null reference is


passed as an argument

SqlException An exception thrown when SQL Server returns a


warning or error, this class is in
System.Data.SqlClient namespace.
IndexOutofRangeException Thrown when you attempt to access beyond an
array’s index

ArrayTypeMismatchException Thrown when attempt to assign wrong type of


element to an array.

InvalidCastException Thrown when an attempt to cast from one data


type to another is invalid
ArithmeticException Thrown exception for arithmetic, casting,
conversion

DivideByZeroException Thrown when attempt to divide a number by zero

StackOverflowException Thrown when the execution stack overflow


because it contains too many nested method
calls.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
94

Examples Program:-

using System;
namespace ConsoleApplication4
{
class Except
{
int a,b,c;

public void accept()


{
Console.WriteLine("Enter Two number");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
}
public void cal()
{
try
{
c = a / b;
Console.WriteLine(" a/b= " + c);
}
catch (Exception e)
{
Console.WriteLine("Exception: "+e.Message);
}

}
}
class ExceptionTest
{
public static void Main()
{
Except obj = new Except();
obj.accept();
obj.cal();
Console.ReadLine();
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
95

In this program if we accept zero for the variable b it shows the exception “ Dived by Zero
Exception”, but after accepting non zero value for the b variable it gives the desired output.
Here try and catch blocks handles one exception divided by zero and doesn’t allow the
program to terminate abnormally.

8.3: try with multiple catch blocks


Handling multiple exception:- we can handle multiple exception by using multiple catch blocks
after one try block. We can use multiple try and catch in a function to handle multiple
exceptions but it doesn’t look good, so instead of that we can use multiple catch with one try
block.

Here is an example:-

try
{
c = a / b;
list[5] = 50;
Console.WriteLine(" a/b= " + c);

}
catch (DivideByZeroException d)
{
Console.WriteLine("Exception: " + d.Message);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception " + ex.Message);
}

Here in the try block first two statements are expected to throw two exceptions which are
handled through two catches. First catch handles the divided by zero exception and the
second one handles the array index out of range exception.
Finally block: - is the block used at the end of all catch statements and executed for sure. It
handles the exception which is not caught by any of the previous catch statement.

try
{
c = a / b;
list[5] = 50;
Console.WriteLine(" a/b= " + c);

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
96

catch (DivideByZeroException d)
{
Console.WriteLine("Exception: " + d.Message);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Exception " + ex.Message);
}

finally
{
Console.WriteLine("End of the program");
}

Throwing our own exception: A user defined exception class which is possible by inheriting a
generic Exception class.

class MyException : Exception


{
public MyException(string str) : base(str)
{
Console.WriteLine("user defined exception called");
}
}

8.4 C# that will read a name from the keyboard and display it on the screen. The
program to throw an exception when the length of the name is more than 15
characters. Program to throw our own exception.

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
class MyException : Exception
{
public MyException(string str)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
97

: base(str)
{
Console.WriteLine("user defined exception called");
}
}
class Exceptionprog
{
static void Main(string[] args)
{
int opt, number1, number2;
string name;
int[] arr = new int[5] { 10, 20, 30, 40, 50 };
do
{
Console.Clear();
Console.WriteLine("illustrating exceptions");
Console.WriteLine("1.divide by zero");
Console.WriteLine("2.array index out of range");
Console.WriteLine("3.user defined exception");
Console.WriteLine("4.exit");
Console.WriteLine("enter an option");
opt = int.Parse(Console.ReadLine());
try
{
switch (opt)
{
case 1: Console.WriteLine("enter ur no");
number1 = int.Parse(Console.ReadLine());
Console.WriteLine("enter number 2");
number2 = int.Parse(Console.ReadLine());
Console.WriteLine("the result of number1 and num2" + number1 /
(number2));
Console.ReadLine();
break;
case 2: Console.WriteLine("array value");

for (int i = 0; i < 7; i++)


{
Console.Write("arr[" + i + "]=");
Console.WriteLine(arr[i]);
}
Console.ReadLine();
break;
case 3: Console.WriteLine("enter a strng <6 char");
name = Console.ReadLine();
if (name.Length > 5)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
98

throw new MyException("the string length should not be more than 5 cahr");
else
Console.WriteLine("entered string is right");
Console.ReadLine();
break;
case 4: break;
}
}

catch (DivideByZeroException e)
{
Console.WriteLine("do not divide a number by zero" + e);
Console.ReadLine();
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("array indx out of range" + e);
Console.ReadLine();
}
catch (MyException e)
{
Console.WriteLine("e.msg" + e);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("exception caught here" + e.Message);
Console.ReadLine();
}
}
while (opt != 4);
Console.ReadLine();
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
99

Chapter #9: Multi Threading


9.1: Thread and multithreading

Like java C# also supports multithreading which enable us to execute multiple part of a
program simultaneously, that part of the program may be a method having any set of
instructions. Multithreading requires using a class “System.Threading.Thread” which has
different functions for different operation on a thread.

9.2 System.Threading .Thread class

The most primitive of all types in System.Threading namespace is Thread. This type
defines a number of methods that allow us to create new threads within the current
Application Domain. It also allows us to suspend, stop, and destroy a particular thread.

Table having some methods/properties of the Thread Class

Methods/Properties Description

Start( ) To start a thread

Abort ( ) It terminates a thread

Interrupt() It interrupt a thread that is in waitsleepjoin state

Join( ) It blocks calling thread until a thread terminates

Resume( ) To resume a suspended thread

Suspend( ) It suspend a thread which can be execute further only


after resume

Sleep( n ) It makes sleep to the thread for a given time, it a static


function that may be called like: Thread. Sleep (5); here

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
100

the thread will sleep for 5 milliseconds.

Name Is a property to assign name to a thread

Priority Is a property to Gets or sets the priority of a thread, which


may be assigned a value from the ThreadPriority
enumeration.

Syntax to call a thread

Thread object_name = new Thread(new ThreadStart(Class_Name.Method_Name));


object_name.Start();

Sample program having two threads

using System.Threading;
public class MyThread
{
public static void Thread1() //thread 1
{
for (int i = 1; i < 100; i++)
{
Console.WriteLine("Thread1 {0}", i);
}
}
public static void Thread2() //thread 2
{
for (int i = 101; i < 200; i++)
{
Console.WriteLine("Thread2 {0}", i);
}
}
}

public class CallThreads


{
public static void Main() //main thread

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
101

{
Console.WriteLine("Before start thread");
Thread tid1 = new Thread(new ThreadStart(MyThread.Thread1));
Thread tid2 = new Thread(new ThreadStart(MyThread.Thread2));
tid1.Start();
tid2.Start();
Console.ReadLine();
}
}

A thread can be interrupted by using function like abort ( ), sleep ( ), suspend ( ) and interrupt
( ).

9.3 A Program to implement Multithreading with interrupting functions

public class MyThread


{
public void Thread1()
{
for (int i = 1; i <= 20; i++)
{
Thread thr = Thread.CurrentThread;
Console.WriteLine(thr.Name + "=" + i);
if (i == 5)
{
try
{
Thread.Sleep(2);
}
catch (ThreadInterruptedException tie) {
Console.WriteLine(tie.ToString() );
}
catch (Exception ae)
{
Console.WriteLine(ae.ToString());
}

}
}
} //end of thread

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
102

public void Thread2()


{
for (int i = 21; i <=40; i++)
{

Thread thr = Thread.CurrentThread;


Console.WriteLine(thr.Name + "=" + i);
if (i == 15)
{

try
{
thr.Abort();
}
catch (Exception ae)
{
Console.WriteLine(ae.Message);
}
}

}
} //end of thread 2

} end of Mythread class

public class Program7


{

public static void Main()


{
Console.WriteLine("Before start thread2");
MyThread2 thr1 = new MyThread2();
MyThread2 thr2 = new MyThread2();
Thread tid1 = new Thread(new ThreadStart(thr1.Thread1) );
Thread tid2 = new Thread(new ThreadStart(thr2.Thread2) );
tid1.Name = "Thread 1";
tid2.Name = "Thread 2";
tid1.Start();
tid2.Start();
Console.WriteLine("End of Main");

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
103

Console.ReadLine();
}
}

9.4 Multithreading program with priority setting

using System;
using System.Threading;
namespace ConsoleApplicatio4
{
public class MyThread
{
public static void Thread1() //thread 1
{
for (int i = 1; i < 100; i++)
{
Console.WriteLine("Thread1 {0}", i);
}
//getting priority
Console.WriteLine("Thread 1 Priority :" + Thread.CurrentThread.Priority.ToString());

}
public static void Thread2() //thread 2
{
for (int i = 101; i < 200; i++)
{
Console.WriteLine("Thread2 {0}", i);
}
Console.WriteLine("Thread 2 Priority :" + Thread.CurrentThread.Priority.ToString());
}
}
public class CallThreads
{
public static void Main() //main thread
{
Console.WriteLine("Before start thread");

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
104

Thread th1 = new Thread(new ThreadStart(MyThread.Thread1));


Thread th2 = new Thread(new ThreadStart(MyThread.Thread2));
th1.Start();
th2.Start();
th1.Priority = ThreadPriority.Highest; //setting priority
th2.Priority = ThreadPriority.AboveNormal;
Console.ReadLine();
}
}
}

Chapter #10: Windows and Web Applications

10.1: Windows application

Windows application give us the form like visual basic to design and then write the code for
it, this application is best suited for the desktop application and very convenient to design
attractive form by drag and drop controls from the given tool box and by using different
properties of the form.

A form represents a class and all controls taken on the form represent methods respectively
in the code. So, the form code will look same as the code we have discussed in the console
application, that’s why we are not going to discuss any coding here, but we must note it that,
we don’t have to write the method definition of any control or the class for the form, all these
appears automatically by just double clicking on the controls of the form. We can also see
the code of the form from the view code icons.

A nice database application project can be designed using windows application, .NET is
having great support of data base, it allows us to connect our program by using ADO.NET
which will be discussed in the next chapter.

Let’s see the steps to start a windows application.

1. Click on “Start” button

2. Click on the option “Microsoft Visual Studio 2010”

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
105

3. We get start page window of visual studio which has the options to open new or existing
projects.

4. Click on the “New Project” option which opens a window with options to choose
language, application type and the project/application name.

5. From the “New Project” window choose C# language and Windows Forms Application
then enter the name of your project and then click on OK button. If we don’t enter the
name it takes by default name of the project as “WindowsFormsApplication1”.

6. After clicking on OK button, our application starts in .NET IDE (integrated development
Environment) with by default form1. Here we can design the form with controls and
properties and run the project by just clicking on the green (start debug) button or
directly by pressing F5 button.

Start page_ Microsoft visual studio’s picture is given below to help and understand the steps,
we can see new project window that is listing all languages supported by .NET framework
4.0 and all different types of applications which can be chosen according to the requirement.
If we wish to go for console application we can choose “Console Application”, for Web we
can choose “ASP.NET Web Application” and so on.

(Start Page with New Project window)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
106

After getting the form we need to design the form using controls and its properties. But
before that we must know about the controls and its properties, most of the controls in .NET
are same as Visual Basic.

Let’s design a login form using some familiar controls like labels, textbox and buttons.

Login form is designed using 6 controls, two labels for user name and password, two
textboxes for the same and two buttons for OK and cancel. In the window we can see one
property of the password text box “PasswordChar” which is given * character which shows
when typing password, this properties allows to hide the password during input, for the rest
controls only “Text” properties are given which are visible like OK and Cancel are the values
of Text property of the Button controls.

10.1.2 Window Controls

Controls are the main tools on the toolbox to design and give action to a form; all controls
are associated with some events and properties, most of the controls have some common
properties like: name, enabled and visible. Below is a list of controls with events and
properties.

Controls Properties Events

Name,backcolor,backgroundimage,flatstyle,f Click, enter, keypress,


ont,tabindex, text. keydown

Name, backcolor, checked, checkstate, font, Click, checkedchanged


enabled, text

Name, allowprop, checkonclick, font, items selectedIndexchanged,


click

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
107

Name, anycolor, color, allowfullopen ----------------------------------


--

Name,backcolor, datasource, SelectedIndexchanged,


displaymember, flatstyle,Items, text , font click,
datasourcechanged.

Items, font, text, name Opening, click

Columns, datasource, datamember, name, Cellcontentclick


enabled.

Name, enabled, font, value, visible. Valuechanged

Name, color, font -----

Text, name Enter

Value, name Scroll

Name, text, font ---

Name, datasource, displaymember, font, SelectedIndexChanged,


Items, SelectedIndex click

Items, font, columns, name SelectedIndexChanged,cl


ick

Name, selectionrange dataChanged,


DateSelected

Image, name Click

Value, name Click

Checked, name, font, text, Click

Text,name,font, passwordChar, multiline, Textchanged, click


readonly

Interval, enabled, name Tick

Items, font, Locked, stretch, Itemclicked, click

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
108

After having looked on these controls, let’s use these controls in different programs.

10.1.3: Program:-To change the font size, colour, name and style by different controls
and its properties.

Controls:

Text box for string entry, ListBox for font name, combo boxes for size and style, radio
buttons for colors.

Values in the ListBox and Combo Boxes.

Font names are assigned to list box by Items property. Similarly size and styles are assigned
to the combo boxes by using Items property.

In windows application first we must design the form then for writing the code for the form,
just double click on the form anywhere. Class and methods appears automatically by just
click on the control, so remember don’t type any function “like private void
button1_Click(object sender, EventArgs e){ }“ it comes automatically, just double click on the
button.

using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
109

{
InitializeComponent();
}

//Format text button


private void button1_Click(object sender, EventArgs e)
{
String font;
if (lstname.SelectedIndex == 0) //To change font name
txtname.Font = new Font("Times New Roman", 10);
else if (lstname.SelectedIndex == 1)
txtname.Font = new Font("Arial", 10);
else
txtname.Font = new Font("Algerian", 10);
font = txtname.Font.Name;
if (cmbsize.SelectedIndex == 0) //To change font size
txtname.Font = new Font(font, 12);
else if (cmbsize.SelectedIndex == 1)
txtname.Font = new Font(font, 14);
else
txtname.Font = new Font(font, 16);
if (cmbstyle.SelectedIndex == 0) //To change font style
txtname.Font = new Font(txtname.Font, FontStyle.Bold);
else if (cmbstyle.SelectedIndex == 1)
txtname.Font = new Font(txtname.Font, FontStyle.Italic);
else
txtname.Font = new Font(txtname.Font, FontStyle.Underline);
if (optred.Checked)
txtname.ForeColor = Color.Red; //To change font color
else if (optblue.Checked)
txtname.ForeColor = Color.Blue;
else
txtname.ForeColor = Color.Green;

}
private void btncancel_Click(object sender, EventArgs e)
{
this.Close();
}

}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
110

After completing a program, we must think to start a new program, for that we need to just
add another window form from project menu (project ->Add Windows Form). And to run that
form we need to change the start up object from project menu (Project -> windowapp1
Properties).

10.1.4: MDI Parent Form: Multiple documents Interface (MDI) is another type of form which
can be added in our project like another form. An MDIForm is a form which consists of menus
and toolbar and used to integrate another forms of project. Generally we use MDIForm in our
project as a main page/home page.

We can create our own MDI Parent form by just changing the value of a property
(“IsMDIContainer=True”) and by using menuStrip and toolStrip controls we can create
menu and tool bar on the form.

Example-

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
111

10.1.5: Program to design a calculator:

using System.Windows.Forms;
namespace calculator
{
public partial class Form1 : Form
{
double val;
public char prevop;

public Form1()
{
InitializeComponent();
}
private void display(String snum)
{

if (prevop == '=')
{
prevop=' ';
txtdisp.Text = " ";
}
if (txtdisp.Text == " ")
txtdisp.Text = snum;
else
txtdisp.Text = txtdisp.Text + snum;
}
private void Form1_Load(object sender, EventArgs e)
{
val = 0.0;
prevop=' ';

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
112

}
private void btn1_Click(object sender, EventArgs e)
{
display(btn1.Text);

private void btn2_Click(object sender, EventArgs e)


{

display(btn2.Text);
}
private void btn3_Click(object sender, EventArgs e)

{
display(btn3.Text);

}
private void btn4_Click(object sender, EventArgs e)
{
display(btn4.Text);

}
private void btn5_Click(object sender, EventArgs e)
{

display(btn5.Text);
}
private void btn6_Click(object sender, EventArgs e)
{
display(btn6.Text);

}
private void btn7_Click(object sender, EventArgs e)
{
display(btn7.Text);

}
private void btn8_Click(object sender, EventArgs e)
{
display(btn8.Text);

}
private void btn9_Click(object sender, EventArgs e)
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
113

display(btn9.Text);

}
private void btn0_Click(object sender, EventArgs e)
{
display(btn0.Text);

private void btnadd_Click(object sender, EventArgs e)


{
prevop = '+';
if (val == 0)
val =val+ Convert.ToDouble(txtdisp.Text);
txtdisp.Text = " ";
}

private void btnsub_Click(object sender, EventArgs e)


{
prevop = '-';
if (val == 0)
val = Convert.ToDouble(txtdisp.Text);
else
val = val - Convert.ToDouble(txtdisp.Text);
txtdisp.Text = " ";
}
private void btndiv_Click(object sender, EventArgs e)
{
prevop = '/';
if(val==0)
val = Convert.ToDouble(txtdisp.Text);
else
val = val / Convert.ToDouble(txtdisp.Text);
txtdisp.Text = " ";
}

private void btnclear_Click(object sender, EventArgs e)


{
txtdisp.Text = " ";
}
private void btnmul_Click(object sender, EventArgs e)
{
prevop = '*';
if(val==0)
val =Convert.ToDouble(txtdisp.Text);
else

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
114

val = val * Convert.ToDouble(txtdisp.Text);


txtdisp.Text = " ";
}
private void btnequal_Click(object sender, EventArgs e)
{
if (prevop == '+')
val = val + Convert.ToDouble(txtdisp.Text);
else if (prevop == '-')
val = val - Convert.ToDouble(txtdisp.Text);
else if(prevop=='*')
val = val * Convert.ToDouble(txtdisp.Text);
else if (prevop == '/')
{
try
{
val = val / Convert.ToDouble(txtdisp.Text);
}
catch(Exception es)
{
MessageBox.Show(es.Message);
}
}
txtdisp.Text = Convert.ToString(val);
prevop = '=';
val = 0.0;

private void btndot_Click(object sender, EventArgs e)


{

if (prevop == '=')
{
prevop = ' ';
txtdisp.Text = " ";
}

if (!txtdisp.Text.Contains("."))
{
if (txtdisp.Text != " ")
txtdisp.Text = txtdisp.Text + ".";
else
txtdisp.Text = "0.";
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
115

}
}

10.1.6: VC# Program to display curent running time using Timer.

using System;
using System.Windows.Forms;

namespace mywindowapplication
{
public partial class currenttime : Form
{
public currenttime()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToLongTimeString();

}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;

}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
116

}
}

10.2: Web Application


.NET framework is an excellent platform for designing and developing a web application, like
a windows application we can design and code for a web application to form an attractive and
dynamic website. For coding we can use any of the different languages supported by the
.NET Framework, when we start a web application in .NET framework we get two types of
code and a design page. One code represents html source code which represents the design
of the page, and other one to implement the action code of the form.

10.2.1: Step to design a web application:

Step1: Start button ->Microsoft Visual studio 2010

Step2: Click on the New Project option

Step3: Select Language for the page and ASP.NET Web Application, click on OK button.

Step4: We get the inbuilt web pages with master page; we can start designing web page
from here.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
117

After designing the page we can run the site by just clicking on start debug or F5 button.

ASP.NET is a server side web designing platform which runs on the IIS web server of
windows operating system; we need not to install any other web server. As we know to run
any other server side scripting languages like JSP/PHP requires installing Apache or glass
fish web server.

10.2.2: HTML source code of the design:

When we drag and drop the controls on the page, automatically the html code for the design
appears in the source, where we can modify the code to change the design.

Once we have designed a home page we need to have many other web pages having the
same style of the home page, ASP.NET provides the facility to add as many web pages in
the web site using the option “Web form using Master Page” from Project menu -
>AddNewItem option.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
118

10.2.3: Masger Page

A master page is an inbuilt home page of the ASP.NET web application, which consists of
inbuilt menus, design and login option for the page. A Master page is used in a web site as a
home page which integrates all other pages with it under the manus or link. The best thing
about a master page is that, it shares the style with all other content pages which are taken in
the site by using master page, and allows us to design uniform pages with the same style and
look. It open bydefault, in .NET 2010 with the start of the web application; it can be added as
well from the project menu.

The Page which is added to the web site using Master page is called content page, a content
page contains the master page style, menu and complete look and provide the space to
design some different contents for the different page.

10.2.4: A Content Page having master page style

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
119

After designing the page if we want to see the page working at the run time, we need to write
the action code for the particular control in C# like a windows application. In this example we
can write the code for order and cancel button.

And the code can be written by double clicking on the buttons:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
120

10.2.5: C# code for the web page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=system\\SQLExpress;Initial
Catalog=mydb;Integrated Security=SSPI");
con.open( );
}
protected void Button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into Items values('" + textBox1.Text + "','" +
textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Your order is placed ! Thanks";
}

protected void Button2_Click(object sender, EventArgs e)

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
121

{
Environment.Exit(0);
}

}
}

10.2.6: Runing the Web Site by just clicking on start debug button or F5 function key.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
122

Chapter #11: ADO.NET

11.1: Introduction to ADO.NET

ADO.NET is the data access technology of the .NET Framework. ADO.NET provides a
common coding structure for accessing data, regardless of the data source. We can connect
to our database by ADO.NET code to access our data.
ADO is short for ActiveX Data Objects, the previous version of the data access technologies,
before the .NET Framework was introduced.

For SQL Server we can use “System.Data.SqlClient” namespace which supports SQL
Server 7.0 or later versions. And as we know that SqlServer Express Edition 2008 comes
inbuilt with .NET Framework4.0 (.NET 2010). For oracle we need to use
“System.Data.OracleClient” namespace. Here we will discuss all examples with the respect
of SQL Server database.

After using ADO.NET namespace System.Data.SqlClient we get lots of classes to support


the database access operations.

Some of the System.Data.SqlClient namespace classes are:

❖ SqlConnection : Represents an open connection to Sql Server database.


❖ SqlCommand: It allows us to execute any SQL query to perform the database
operations.
❖ SqlDataAdapter: Represents a set of data commands and a database connection that
are used to fill System.Data.DataSet and update an SQL server database.
❖ SqlDataReader : Provides a way of reading forward-only stream of row from SQL Server
Database. Its object stores the rows after executing select query.
❖ SqlCommandBuilder:Autometically generates single table command that are used to
reconcile changes made in System.Data.DataSet, we use this class with SqlDataAdapter
to fill the columns of a grid.
❖ SqlBulkCopy: It allows us efficiently bulk load of a SQL Server Table with data from
another source.
❖ SqlException: To handle exception related to SQL Connection and data access
operation.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
123

11.2: Connecting to the database


We use the connection object for our data provider to connect to our data source. As we can
imagine, connecting to a data source is a prerequisite for retrieving data from the data
source.
We use a connection object to:

✓ Pass a connection string to the connection object. A connection string


includes our username and password for accessing the data source. The
connection object sends the connection string to the data source for validation.

✓ Open the connection. Opening a connection allows us to communicate with the


data source.

✓ Send commands by using the connection. Send queries to retrieve and update
the data source.

✓ Close the connection. Each connection to the data source consumes resources
on the server. Always close the connection as soon as you execute your
commands.

1 . Create a new SqlConnection connection object.


To create the new SqlConnection object Con, type the following lines of code in the Code
Editor:

SqlConnection Con =new SqlConnection( );

2 . Create a new connection string to connect to an SQL Server 2008


database.
The connection string to connect to the Adventure Works sample database installed on a
local instance of SQL Server 2008 Express Edition using integrated security is
Data Source=(local)\\sqlexpress;Initial Catalog=DBName;IntegratedSecurity=True
Visual Studio provides many tools for building connection strings.

3. Assign the connection string as we create in Step 2 to the Connection


String property of the Con SqlConnection object, as shown in the following example:
Con.ConnectionString = “Data Source=(local)\\sqlexpress;Initial
Catalog=DBName;IntegratedSecurity=True”;

4. Call the Open method in Con to open the database connection with the following
line:
Con.Open();
5. Call the Close method in MyConnection to close the database connection
with the following line:
Con.Close();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
124

Here’s the entire code listing for the preceding code example:
Using System.Data.SqlClient; // namespace using
SqlConnection Con =new SqlConnection();
Con.ConnectionString = “Data Source=(local)\\sqlexpress;Initial
Catalog=DBName;IntegratedSecurity=True”;
Con.Open();
Con.Close();

11.3: Creating database in SQL Server.

Steps to start the SQL Server Query Editor:

Step1: Click on the Data menu of the .NET IDE


Step2: Click on the Transaction-SQL Editor option
Step3: Click on the New Query Connection

Step4: Connect to server window appears with automatically filled values in the server type,
name and authentication. CMR\SQLExpress is server name where CMR is my system name.
Click on the connect button.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
125

Step5: Write the query in the SQL Query editor and run one by one query by clicking on the
execute button or by pressing short key (Ctrl + Shift + E)

If we have written multiple query lines in the editor, at a time one query at a time must be
selected to run otherwise it runs the first query by default.

Let’s create a database MYDB with two tables Login and Employee.

//creating a database MYDB.


Create database MYDB;
//using the database MYDB to create tables in it.
use MYDB;
//creating Login table
Create table Login(username varchar(12)Primary key, Pass varchar(12));
//Creating Employee table
Create table Employee(Eid int Primary key, name varchar(12),designation varchar(12), salary
int);
To run these query in .NET SQL Query Editor we need to select one query at a time and
press (Ctrl + Shift +E) or we can press execute Query button.

We have got the database lets design and code for Login form.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
126

11.4: Login code to validate user and password


using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
SqlConnection con;
SqlCommand cmd;
public Form1()
{
InitializeComponent();

}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=CMR\\SQLExpress;Initial
Catalog=MYDB;Integrated Security=true");
con.Open();
cmd = new SqlCommand("select count(*) from Login where
username='"+textBox1.Text+"' and pass='"+textBox2.Text+"'",con);
object n;
n = cmd.ExecuteScalar();
int res;
res = (int)n;
if (res > 0) {
MessageBox.Show("valid user");
}
else {
MessageBox.Show("invalid user");
}

}
}
}

11.5: SQLCommnd and its functions: We have different types of sql queries, some query
returns rows form the table, some returns the number like count and some queries does’t
retrun any thing. All these queries cann’t be executed by any one function. To execute all
these queries SQLCommnd is having different functions.

For examples:
1. Select * from tablename; returns rows which can be executed by

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
127

ExecuteReader( ) function.
2. Select count(*) from tablename; returns number which can be executed by
ExecuteScalar( ) function.

3. Insert into tablename values( “data”); can be executed by ExecuteNonQuery( )


function.
4. Similarly update, delete, alter queries can be executed by ExecuteNonQuery( )
function.

Above ExecuteScalar( ) function is used to execute the query which returns the count. Lets
use other functions in different examples.

11.6: VC# program to add Employee record to the database

Table: Create table Employee(Eid int Primary key, name varchar(12),designation


varchar(12), salary int);

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace myproject
{
public partial class Form1 : Form
{
SqlConnection con;
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
128

private void Form1_Load(object sender, EventArgs e)


{
con = new SqlConnection("Data Source=CMR\\SQLExpress;Initial
Catalog=MYDB;Integrated Security=true");
con.Open();
}

//Code for ADD button


private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into Employee values('" + textBox1.Text +
"','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record inserted");

}
//Exit button
private void button3_Click(object sender, EventArgs e)
{
con.Close();
Environment.Exit(0);

}
//Clear button
private void button2_Click(object sender, EventArgs e)
{
Textbox1.text=””;
Textbox2.text=””;
Textbox3.text=””;
Textbox4.text=””;

}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
129

11.7: VC# Program to search and delete Employee Record

//Code to search and delete recod


using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace myproject
{
public partial class update : Form
{
SqlConnection con1;
SqlCommand cmd1;
SqlDataReader dr;
public update()
{
InitializeComponent();
}
private void update_Load(object sender, EventArgs e)
{
con1 = new SqlConnection("Data Source=CMR\\SQLExpress;Initial
Catalog=MYDB;Integrated Security=true");
con1.Open();
}
private void searchbtn_Click(object sender, EventArgs e)
{
cmd1 = new SqlCommand("select * from emp where ino='" + textBox1.Text +
"' ", con1);
dr = cmd1.ExecuteReader();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
130

if (dr.Read())
{
textBox2.Text = dr.GetValue(0).ToString();
textBox3.Text = dr.GetString(1);
textBox4.Text = dr.GetValue(2).ToString();
textBox5.Text = dr.GetString(3);
}
else
MessageBox.Show("Record not found");
}
private void deletebtn_Click(object sender, EventArgs e)
{
cmd1 = new SqlCommand("delete from emp where ino='" + textBox1.Text + "' ");
cmd1.EndExecuteNonQuery();
MessageBox.Show("Record Deleted");
}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
131

Chapter #12:
Sample Project (A Human Resource Management System)
12.1: Introduction to the Project

“Human Resource Management System” is a system to manage the information about the
human resources, trainee, department and projects in a software development company,
where many people may be deployed on various running projects. Different departments
detail with head and employees. Projects detail status with employee deployed on the project
are maintained. Administrator can use this system for maintaining all these detail, and can
also manage the salary and appraisal of employees as well as changing the password for the
system security.

This project is just a test project to implement a human resource management system for a
company to help the manager to manage all information related to human resources. As we
know manually it’s difficult to manage and retrieve information in quick time, this system is an
effort to solve this problem.

Modules of the project are:

❖ Employee Master
❖ Department Master
❖ Project
❖ Work_On
❖ Training
❖ Administrator
Employee Master Deals with the employee detail and functions on data like addition,
updating, deletion search and display.

Department Master module deals with the department detail and operations on the
department like adding department, search, edit and display.

Project Module maintains the status of the projects, Human resources on the projects, and
adding, editing a project.

Work_On module is to deploy employee from various department on various projects.

Training module is to deals with the detail of the trainees in the company.

Administrator module is to do the appraisal of the HR and to change user and password.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
132

12.2: Database of the HRM System:

create database hrm;

use hrm;
create table login(username varchar(12),pass varchar(12));

create table emplyee(eid int primary key,name varchar(15),designation varchar(15),doj


date,dept varchar(10),salary int);

create table dept(dname varchar(10) primary key,head varchar(15),addess varchar(30));

create table project(pid int primary key,ptitle varchar(15),sdate date,tdate date,budget int);

create table workon1(eid int references employee(eid) on delete cascade,pid int references
project(pid) on delete cascade);

create table training(tno int primary key,tdate date,dept varchar(10),attendance int,topics


varchar(15),trainer varchar(15),tcontact varchar(20));

Form Design/snap Short and VC# coding for the same:

Login Form

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
133

12.3: Login Code:

using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class loginfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public loginfrm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("select * from login where username='"+textBox1.Text+"'
AND pass='"+textBox2.Text+"'",con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Home_mdi hm = new Home_mdi();
this.Hide();
hm.Show();
}
else
{
MessageBox.Show("Invalid User/Password");
textBox1.Text = "";
textBox2.Text = "";
dr.Close();
}
}
private void loginfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
private void button2_Click(object sender, EventArgs e)
{
con.Close();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
134

this.Dispose();
}
}
}
12.4: MDIParent Form

Menu and options of the form are:

Employee_Master Menu -> options are Emp_Centre and Emp_Show

Dept_Master Menu -> It doesn’t contain any options but directly connected to the
dept_form.

Project Menu -> options are New_Project, HR_on_Project, Project_status and finished
project.

Work_On Menu -> options in this menu are Emp_Deployement and Emp_Status.

Trainee Menu -> It has two options Trainee and trained.

Admin Menu -> It has two options for Emp_Appraisal and for changing password.

Exit Menu -> To exit the application.

If we click on any option on the MDIParent form the related form opens inside the MDI form,
Closing child doesn’t affect the MDIParent form. That’s the reason we must have a parent
form to hold and integrate other child forms.

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
135

MDIParent Code: It has the code to integrate other forms from menus and the options.

using System.Windows.Forms;

namespace HRM
{
public partial class Home_mdi : Form
{
private int childFormNumber = 0;

public Home_mdi()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0); //To exit the application
}
private void empCentreToolStripMenuItem_Click(object sender, EventArgs e)
{
Empfrm ef = new Empfrm(); //To open the Employee form
ef.Show();
}
private void empShowToolStripMenuItem_Click(object sender, EventArgs e)
{
EmpViewfrm ev = new EmpViewfrm();
ev.Show();
}
private void newProjectToolStripMenuItem_Click(object sender, EventArgs e)
{
NewProj np = new NewProj();
np.Show();
}
private void projectRequirementToolStripMenuItem_Click(object sender, EventArgs e)
{
HRonProj hr = new HRonProj();
hr.Show();
}
private void projectStatusToolStripMenuItem_Click(object sender, EventArgs e)
{
ProjStatusfrm ps = new ProjStatusfrm();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
136

ps.Show();
}

private void finishedProjectsToolStripMenuItem_Click(object sender, EventArgs e)


{
Finishedprojfrm fp = new Finishedprojfrm();
fp.Show();
}
private void empDeployementToolStripMenuItem_Click(object sender, EventArgs e)
{
EmpDepfrm ed = new EmpDepfrm();
ed.Show();
}
private void empStatusToolStripMenuItem_Click(object sender, EventArgs e)
{
Emp_statusfrm es = new Emp_statusfrm();
es.Show();
}
private void traineeToolStripMenuItem_Click(object sender, EventArgs e)
{
Traineefrm tf = new Traineefrm();
tf.Show();
}
private void trainedToolStripMenuItem_Click(object sender, EventArgs e)
{
Trainedfrm tf = new Trainedfrm();
tf.Show();
}
private void hikeSalaryToolStripMenuItem_Click(object sender, EventArgs e)
{
EmpAppfrm emf = new EmpAppfrm();
emf.Show();
}
private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
{
changePassfrm cpf = new changePassfrm();
cpf.Show();
}
private void deptMasterToolStripMenuItem_Click(object sender, EventArgs e)
{
Deptfrm df = new Deptfrm();
df.Show();
}
private void internsToolStripMenuItem_Click(object sender, EventArgs e)
{
internsfrm inf = new internsfrm();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
137

inf.Show();
}
}
}

12.5: Employee Form

Employee form Code:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Empfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public Empfrm()
{
InitializeComponent();
}
private void Empfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
button2.Text = "AddNew";
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
138

private void button1_Click(object sender, EventArgs e)


{
cmd = new SqlCommand("Select * from employee where eid='" + textBox1.Text + "'",
con);
dr = cmd.ExecuteReader();

if (dr.Read())
{
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
dateTimePicker1.Text = dr.GetValue(3).ToString();
textBox4.Text = dr.GetValue(4).ToString();
textBox5.Text = dr.GetValue(5).ToString();
textBox6.Text = dr.GetValue(6).ToString();
}
else
MessageBox.Show("ID Not Found");
dr.Close();
}
private void button2_Click(object sender, EventArgs e)
{
if (button2.Text == "AddNew")
{
cmd = new SqlCommand("select max(eid) from employee", con);
dr = cmd.ExecuteReader();
dr.Read();
int id = int.Parse(dr.GetValue(0).ToString());
id++;
button2.Text = "Save";
dr.Close();
Clear();
textBox1.Text =id.ToString();

else if (button2.Text == "Save" && textBox2.Text!="")


{

cmd = new SqlCommand("insert into employee values("+textBox1.Text+",'" +


textBox2.Text + "','" + textBox3.Text + "','" + dateTimePicker1.Value + "','" + textBox4.Text +
"','" + textBox5.Text + "','" + textBox6.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Inserted");
button2.Text = "AddNew";

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
139

Clear();
}
}
private void button3_Click(object sender, EventArgs e)
{
string qry = "update employee set
name='"+textBox2.Text+"',designation='"+textBox3.Text+"',doj='"+dateTimePicker1.Value+"',
dept='"+textBox4.Text+"',spl='"+textBox5.Text+"',salary='"+textBox6.Text+"' where
eid="+textBox1.Text+" ";
cmd = new SqlCommand(qry,con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
}

private void button4_Click(object sender, EventArgs e)


{
if (MessageBox.Show("Really delete?", "Confirm delete",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (textBox1.Text == "")
MessageBox.Show("Enter EID");
else
{
cmd = new SqlCommand("delete from employee where eid=" + textBox1.Text + "
", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
Clear();
}
}
}
private void button5_Click(object sender, EventArgs e)
{
Clear();
}
public void Clear()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
dateTimePicker1.Text = "1/1/1900";

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
140

}
}

12.6: Employee View Form:

Employee View Form’s Code:

using System.Windows.Forms;
using System.Data.SqlClient;

namespace HRM
{
public partial class EmpViewfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;

public EmpViewfrm()
{
InitializeComponent();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
141

private void EmpViewfrm_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
cmd = new SqlCommand("select dept from employee",con);
dr = cmd.ExecuteReader();
while (dr.Read())
comboBox1.Items.Add(dr.GetValue(0).ToString());
dr.Close();
}

private void button1_Click(object sender, EventArgs e)


{
da = new SqlDataAdapter("select * from employee where
dept='"+comboBox1.Text+"'", con);
cb = new SqlCommandBuilder(da);

dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;

dataGridView1.DataSource = bs;
}
}
}

12.7: Department Form:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
142

Code of the department form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Deptfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//Objects for connecting datagridview
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;

public Deptfrm()
{
InitializeComponent();
}
//search button
private void button4_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("Select * from dept where dname='" + textBox1.Text + "'",
con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
143

}
else
MessageBox.Show("Dept Name Not Found");

dr.Close();
}

private void Deptfrm_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();

//Addnew/Save Button
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Add_New_Dept")
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox1.Focus();
button1.Text = "Save";
}

else if (button1.Text == "Save" && textBox1.Text != "")


{

cmd = new SqlCommand("insert into dept values('" + textBox1.Text + "','" +


textBox2.Text + "','" + textBox3.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("New Dept. Added");
button1.Text = "Add_New_Dept";
Clear();

}
}
//Update button
private void button2_Click(object sender, EventArgs e)
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
144

string qry = "update dept set head='" + textBox2.Text + "',addess='" + textBox3.Text +


"' where dname='" + textBox1.Text + "' ";
cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
}
//delete button code
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Really delete?", "Confirm delete",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (textBox1.Text == "")
MessageBox.Show("Enter Dept Name");

else
{
cmd = new SqlCommand("delete from dept where dname='" + textBox1.Text + "'
", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
Clear();
}
}
}

private void button5_Click(object sender, EventArgs e)


{
da = new SqlDataAdapter("select * from dept", con);
cb = new SqlCommandBuilder(da);

dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;

dataGridView1.DataSource = bs;
}
public void Clear()
{
textBox1.Text = "";

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
145

textBox2.Text = "";
textBox3.Text = "";

}
}
}

12.8: New Project form for adding and editing projects:

Code for New Project form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class NewProj : Form

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
146

{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public NewProj()
{
InitializeComponent();
}
private void NewProj_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}

private void button1_Click(object sender, EventArgs e)


{
cmd = new SqlCommand("Select * from project1 where pid=" + textBox1.Text + " ",
con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr.GetValue(1).ToString();
textBox3.Text = dr.GetValue(2).ToString();
textBox7.Text = dr.GetValue(3).ToString();
dateTimePicker1.Text = dr.GetValue(4).ToString();
dateTimePicker2.Text = dr.GetValue(5).ToString();
textBox6.Text = dr.GetValue(6).ToString();

}
else
MessageBox.Show("Project Id Not Found");

dr.Close();
}

private void button2_Click(object sender, EventArgs e)


{
if (button2.Text == "AddNew")
{
cmd = new SqlCommand("select max(pid) from project1", con);
dr = cmd.ExecuteReader();
dr.Read();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
147

int id = int.Parse(dr.GetValue(0).ToString());
id++;
button2.Text = "Save";
dr.Close();
Clear();
textBox1.Text = id.ToString();

else if (button2.Text == "Save" && textBox2.Text != "")


{

cmd = new SqlCommand("insert into project1 values(" + textBox1.Text + ",'" +


textBox2.Text + "','" + textBox3.Text + "','" + textBox7.Text + "','" + dateTimePicker1.Value +
"','" + dateTimePicker2.Value + "'," + textBox6.Text + ",'"+comboBox1.Text+"')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Project Saved");
button2.Text = "AddNew";
Clear();

}
}

private void button3_Click(object sender, EventArgs e)


{
string qry = "update project1 set ptitle='" + textBox2.Text + "',technology='" +
textBox3.Text + "',customer='" + textBox7.Text + "',sdate='" + dateTimePicker1.Value +
"',fdate='" + dateTimePicker2.Value + "',budget=" + textBox6.Text +
",status='"+comboBox1.Text+"' where pid="+textBox1.Text+" ";

cmd = new SqlCommand(qry, con);


cmd.ExecuteNonQuery();
MessageBox.Show("Project Updated");
}
private void button4_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Really want to delete?", "Confirm delete",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (textBox1.Text == "")
MessageBox.Show("Enter PID");
else
{
cmd = new SqlCommand("delete from project1 where pid=" + textBox1.Text + "
", con);
cmd.ExecuteNonQuery();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
148

MessageBox.Show("Record Deleted");
Clear();
}
}
}
public void Clear()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox7.Text = "";
textBox6.Text = "";
dateTimePicker1.Text = "1 / 1 / 2000";
dateTimePicker2.Text = "1 / 1 / 2000";
}
}
}
12.9: HR_On_Project Form:

Code for HR on project Form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class HRonProj : Form
{

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
149

SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public HRonProj()
{
InitializeComponent();
}

private void HRonProj_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
cmd = new SqlCommand("select ptitle from project1", con);
dr = cmd.ExecuteReader();
while (dr.Read())
comboBox1.Items.Add(dr.GetValue(0).ToString());
dr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select e.eid,name,designation,spl,dept,ptitle from
employee e, project1 p,workon1 w where ptitle='" + comboBox1.Text + "' AND w.pid=p.pid
AND w.eid=e.eid ", con);
cb = new SqlCommandBuilder(da);

dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;

dataGridView1.DataSource = bs;
}
}
}

12.10: Project status Form:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
150

Code for the ProjStatus form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class ProjStatusfrm : Form
{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public ProjStatusfrm()
{
InitializeComponent();
}
private void ProjStatusfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
da = new SqlDataAdapter("select * from project1", con);
cb = new SqlCommandBuilder(da);

dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
151

}
}
}

12.11: Finished Project Form:

Code is similar to project status form.

12.12: Employee Deployment form:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
152

Code for Emp_Dep_Frm From:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class EmpDepfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public EmpDepfrm()
{
InitializeComponent();
}
private void EmpDepfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}
private void button1_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from employee where dept='" + comboBox1.Text +
"' AND spl='" + comboBox2.Text + "' ", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
153

da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
private void button2_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("insert into workon1
values("+textBox1.Text+","+comboBox3.Text+")",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Done");
da = new SqlDataAdapter("select * from workon1", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView2.DataSource = bs;
}
}
}

12.13: Employee status form design and code is similar to Employee View form except
it selects information from multiple tables:

Code to get the status of employees working on different projects:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Emp_statusfrm : Form

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
154

{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public Emp_statusfrm()
{
InitializeComponent();
}
private void Emp_statusfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}

private void button1_Click(object sender, EventArgs e)


{
da = new SqlDataAdapter("select e.eid,name,designation,spl,dept,ptitle as
working_On from employee e, project1 p,workon1 w where dept='" +
comboBox1.Text + "' AND w.eid=e.eid AND w.pid=p.pid ", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
}
}

12.14: Trainee Form:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
155

Code for the trainee form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Traineefrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public Traineefrm()
{
InitializeComponent();
}

private void Traineefrm_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
cmd = new SqlCommand("select name from employee",con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr.GetString(0));

}
dr.Close();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
156

private void button2_Click(object sender, EventArgs e)


{
cmd = new SqlCommand("Select * from trainee where tid='" + textBox1.Text + "'",
con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
textBox2.Text = dr.GetString(1);
textBox3.Text = dr.GetString(2);
dateTimePicker1.Text = dr.GetValue(3).ToString();
textBox5.Text = dr.GetString(4);
comboBox1.Text = dr.GetString(5);
}
else
MessageBox.Show("Project ID Not Found");

dr.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "AddNew")
{
cmd = new SqlCommand("select max(tid) from trainee", con);
dr = cmd.ExecuteReader();
dr.Read();
int id = int.Parse(dr.GetValue(0).ToString());
id++;
button1.Text = "Save";
dr.Close();
Clear();
textBox1.Text = id.ToString();

else if (button1.Text == "Save" && textBox2.Text != "")


{
cmd = new SqlCommand("insert into trainee values(" + textBox1.Text + ",'" +
textBox2.Text + "','" + textBox3.Text + "','" + dateTimePicker1.Value + "','" + textBox5.Text +
"','" + comboBox1.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Inserted");
button1.Text = "AddNew";
Clear();

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
157

private void button3_Click(object sender, EventArgs e)


{
string qry = "update trainee set name='" + textBox2.Text + "',college='" +
textBox3.Text + "',doj='" + dateTimePicker1.Value + "',project='" + textBox5.Text + "',guide='"
+ comboBox1.Text + "' where tid=" + textBox1.Text + " ";
cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated");
}

private void button4_Click(object sender, EventArgs e)


{
if (MessageBox.Show("Really delete?", "Confirm delete",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (textBox1.Text == "")
MessageBox.Show("Enter Trainee ID");
else
{
cmd = new SqlCommand("delete from trainee where tid=" + textBox1.Text + " ",
con);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
Clear();
}
}
}

public void Clear()


{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox5.Text = "";
dateTimePicker1.Text = "1/1/1900";
comboBox1.Text = "Select Guide";

}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
158

12.15: Trained Form:

Code for Trained form:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class Trainedfrm : Form
{
SqlConnection con;
SqlDataAdapter da = null;
SqlCommandBuilder cb = null;
DataTable dt = null;
BindingSource bs = null;
public Trainedfrm()
{
InitializeComponent();
}

private void Trainedfrm_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
dateTimePicker1.CustomFormat="dd/MM/yyyy";

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
159

dateTimePicker1.Format = DateTimePickerFormat.Custom;

dateTimePicker2.CustomFormat = "dd/MM/yyyy";
dateTimePicker2.Format = DateTimePickerFormat.Custom;

}
//Trainee between the dates
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "Trainee List between the Above Dates";
da = new SqlDataAdapter("select * from trainee where doj between '" +
dateTimePicker1.Value + "' AND '" + dateTimePicker2.Value + "' ", con);
cb = new SqlCommandBuilder(da);

dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;

dataGridView1.DataSource = bs;
}
//All Trainee
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "All Trainee Details";
da = new SqlDataAdapter("select * from trainee", con);
cb = new SqlCommandBuilder(da);
dt = new DataTable();
da.Fill(dt);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
}
}
}

12.16: Appraisal Form

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
160

Code of Appraisal form:

using System.Windows.Forms;
using System.Data.SqlClient;

namespace HRM
{
public partial class EmpAppfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public EmpAppfrm()
{
InitializeComponent();
}

private void EmpAppfrm_Load(object sender, EventArgs e)


{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
//code to assing the dept name from database to combo boxe
cmd = new SqlCommand("select dname from dept", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr.GetString(0));
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
161

dr.Close();
}
//Code increase salary of a dept.
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update employee set salary=salary+'"+textBox1.Text+"'
where dept='"+comboBox1.Text+"' ",con);
cmd.ExecuteNonQuery();
MessageBox.Show(textBox1.Text +" Increament is done for the dept
"+comboBox1.Text);
}
//To increase salary for one employee
private void button2_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("update employee set salary=salary+'"+textBox2.Text+"'
where eid=" +textBox3.Text + " ", con);
int r= cmd.ExecuteNonQuery();
if (r == 1)
MessageBox.Show(textBox2.Text+" Increament is done for the Employee: " +
textBox3.Text);
else
MessageBox.Show("Invalid Employee ID");
}
private void textBox3_Leave(object sender, EventArgs e)
{
cmd = new SqlCommand("select name from employee where eid="+textBox3.Text+"
", con);
dr = cmd.ExecuteReader();
dr.Read();
textBox4.Text = dr.GetString(0);
dr.Close();
}
}
}

12.17: Change Password Form:

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
162

Code for changing password:

using System.Windows.Forms;
using System.Data.SqlClient;
namespace HRM
{
public partial class changePassfrm : Form
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
public changePassfrm()
{
InitializeComponent();
}
private void changePassfrm_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=cmr\\sqlexpress;initial
catalog=HRM;integrated security=true;");
con.Open();
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
163

//Change Password button (OK)


private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("select * from login where pass='" + textBox1.Text + "'",
con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
if (textBox2.Text == textBox3.Text)
{
dr.Close();
cmd = new SqlCommand("update login set pass='" + textBox3.Text + "' where
pass='" + textBox1.Text + "'",con);
cmd.ExecuteNonQuery();
MessageBox.Show("Password changed successfully");
}
else
MessageBox.Show("Confirm password not matched");
}
else
{
MessageBox.Show("Invalid password");
}
if(dr.IsClosed==false)
dr.Close();
}
//cancel button
private void button2_Click(object sender, EventArgs e)
{
con.Close();
this.Dispose();
}
}
}

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication
164

Bibliography

1. Visual Studio 2010 by Andrew Moore


2. Programming in C# a primer, Tata McGraw Hill, E. Balagurusamy.
3. Professional C# 2008, Wrox, Nagel, Evjen, Glynn, Watson, Skinner.
4. Visual studio 2010, the .NET Framework 4.0

Copyright @ Aurangjeb Khan, CMR, Bangalore, C# Programming, 2013, Subhas Store Publication

You might also like