0% found this document useful (0 votes)
44 views

Unit 1 C#

C# is an object-oriented programming language developed by Microsoft that enables developers to build secure and robust applications. It simplifies C++ and is a modern, type-safe language that provides features like interoperability, scalability, and a rich library. C# code runs on the .NET Framework, which includes technologies like Windows Forms, ASP.NET, and LINQ that help develop desktop and web applications. The Common Language Runtime (CLR) converts C# code into machine-readable code and manages memory and execution.

Uploaded by

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

Unit 1 C#

C# is an object-oriented programming language developed by Microsoft that enables developers to build secure and robust applications. It simplifies C++ and is a modern, type-safe language that provides features like interoperability, scalability, and a rich library. C# code runs on the .NET Framework, which includes technologies like Windows Forms, ASP.NET, and LINQ that help develop desktop and web applications. The Common Language Runtime (CLR) converts C# code into machine-readable code and manages memory and execution.

Uploaded by

RAVI MAVARKAR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

UNIT 1 C#

Unit 1

1. Introduction to C#

 ‘C#’ (pronounced as ‘C Sharp’) is an elegant and type safe object oriented language that
enables developers to build a variety of secure and robust application that run on the .Net
Framework.
 It is fully object oriented language.
 C# syntax simplifies many of the complexities of C++.
 C# developed by ‘Anders Hejlberg’ and Microsoft team in 2000.
 So it’s a product of Microsoft.
 It is case-sensitive language.
 It simplifies and modernizes C++.
 It is brand new language derived from the C/C++ family.

C# Features

C# is object oriented programming language. It provides a lot of features that are given below.

1. Simple
2. Modern programming language
3. Object oriented
4. Type safe
5. Interoperability
6. Scalable and Updateable
7. Component oriented
8. Structured programming language
9. Rich Library
10. Fast speed

KLE’S COLLEGE OF BCA GOKAK Page 1


UNIT 1 C#

Fig:Features of C#

1) Simple

C# is a simple language in the sense that it provides structured approach (to break the problem into parts), rich
set of library functions, data types etc.

2) Modern Programming Language

C# programming is based upon the current trend and it is very powerful and simple for building scalable,
interoperable and robust applications.

3) Object Oriented

C# is object oriented programming language. OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to manage if code grows as project size grow.

4) Type Safe

C# type safe code can only access the memory location that it has permission to execute. Therefore it improves
a security of the program.

5) Interoperability

Interoperability process enables the C# programs to do almost anything that a native C++ application can do.

KLE’S COLLEGE OF BCA GOKAK Page 2


UNIT 1 C#

6) Scalable and Updateable

C# is automatic scalable and updateable programming language. For updating our application we delete the old
files and update them with new ones.

7) Component Oriented

C# is component oriented programming language. It is the predominant software development methodology


used to develop more robust and highly scalable applications.

8) Structured Programming Language

C# is a structured programming language in the sense that we can break the program into parts using functions.
So, it is easy to understand and modify.

9) Rich Library

C# provides a lot of inbuilt functions that makes the development fast.

10) Fast Speed

The compilation and execution time of C# language is fast.

1. Net Architecture

KLE’S COLLEGE OF BCA GOKAK Page 3


UNIT 1 C#

2.1 Windows Workflow Foundation (WWF)

 WF is a technology introduced by Microsoft which provides a programming model for


developing workflow based applications on windows.
 The most important features of WF is the separation between the business process code
and the actual implementation code.
2.2 Windows Presentation Foundation (WPF)
 It provides the base for building application and a clear separation between the user
interface and the business logic.
 It helps to building interfaces that include documents, media, tow-and three-dimensional
graphics, animation, web-like characteristics and much more.

2.3 Windows Communication Foundation


 It is one of the new technologies introduced by Microsoft in .Net framework 3.0 for
building and running connected system.
 WCF is a service-oriented technology for developing application.
 The services-oriented design results in a distributed system that runs between the services
and clients.

2.4 Windows CardSpace


 Windows CardSpace (WCS) is a client software introduced by Microsoft that simplifies
the process of accessing resources and also ensure safety of resources.
 It is helps in sharing personal information over the internet.
 It helps programmers develop web sites and software that are less prone to identity-related
attacks, such as phishing.
 WCS helps in reducing the problems related to traditional online security mechanism by
relying less on the user name and passwords and instead using a separate desktop and
cryptographically strong authentication.
 Two types of cards are available –
 Personal Cards – Based on the self-issued identity provides

KLE’S COLLEGE OF BCA GOKAK Page 4


UNIT 1 C#

 Managed Code – Based on identity providers provided by vendors other than


Microsoft.
2.5 LINQ (Language Integrated Query)
 LINQ is one of the components of Microsoft .Net framework 3.5 which adds
native data-querying capabilities to .Net language using a syntax similar to SQL.

2.6 Metadata

 Metadata in .Net is binary information which describes the characteristics of a


resource.
 This information include description of the assembly, data type and
members with their declarations and implementations, references to other
types and members, security permissions etc.
2.7 Assembly

 Microsoft .Net assembly is a logically unit of code, it contains code that


the common language runtime (CLR) executes.
 Assembly is really a collection of types and resource information that are
built to work together and form a logical unit of functionality.
 During the compile time metadata is created with Microsoft Intermediate
Language (MSIL) and stored in a file called a manifest.

2.8 Windows Forms

 Windows forms is the graphical representations of any window displayed in an


application.
 It is included as a part of Microsoft .Net Framework.

2.9 ASP.Net and ASP.Net AJAX

 ASP.Net it is used to deliver interactive, data-driven web application over the


internet.
 It also consists of a large number of controls such as textbox, button and labels.

KLE’S COLLEGE OF BCA GOKAK Page 5


UNIT 1 C#

Net Framework

 .Net framework is execution or runtime environment of .Net program or


application.
 To execute .Net application on any machine/device we required software
known as .Net Framework.
 .Net application will execute under framework only.
 Framework work is a software which will masks (acting as) the
functionality of operating system making the Common Intermediate
Language Code to execute under its control.

KLE’S COLLEGE OF BCA GOKAK Page 6


UNIT 1 C#

Common Language Runtime (CLR)

 CLR is an execution engine of .Net framework in which every application of .Net will runs
under the control of Common Language Runtime (CLR).
 The main function of Common Language Runtime (CLR) is to convert the Managed code
into Native Code and then execute the program.
 The managed code compiled only when it needed that is it converts the appropriate
instructions when each function is called.
 The Common Language Runtime (CLR)’s Just-In-Time (JIT) compilation converts
Microsoft Intermediate Language (MSIL) to native code on demand at application run
time.
 During the execution of program the Common Language Runtime (CLR) manages
memory, Thread execution, Garbage Collection (GC), Exception Handling, Common Type
System (CTS), code safety verification, and other system services.

Microsoft Intermediate Language (MSIL)

 In .Net programming language the source code once compiled will get an Intermediate
Code known as Intermediate code (IL) / Common Intermediate Language (CIL) / Microsoft
Intermediate Language (MSIL).
 This intermediate code will be delivered to the client machine to be converted as machine
code according to client Operating System under the control of .Net executing engine
known as Common Language Runtime (CLR).

KLE’S COLLEGE OF BCA GOKAK Page 7


UNIT 1 C#

Just-In-Time (JIT) Compiler

 The .Net languages which is conforms to the Common Language Specification (CLS) uses
its corresponding runtime to run the application on different Operating System.
 During the code execution time the managed code compiled only when it is needed that is
it converts the appropriate instructions to the native code for execution just before when
each function this process called Just-In-Time (JIT) the common language runtime (CLR)
doing this task.
 The common language runtime (CLR) provides various Just-In-Time (JIT) and each work
on a different architecture depending on Operating System.


Executio
 n

Fig. JIT execution

MSIL (Microsoft Intermediate Language)


 The same Microsoft intermediate language (MSIL) can be executed on different operating
system without rewrite the source code.
 Just-In-Time compiler (JIT) code generally offers far better performance than interpreters.
 In JIT execution happens one-by-one.

KLE’S COLLEGE OF BCA GOKAK Page 8


UNIT 1 C#

The Framework Class Library (FCL)

 The .Net framework class library (FCL) provides the core functionality or .Net Framework
architecture.
 The .Net framework class library (FCL) includes a huge collection of reusable classes,
interfaces and value types.
 The .Net framework class library (FCL) organized in a hierarchical tree structure and it is
divides into Namespace.
 Framework Class Library (FCL) provides the consistent base type that are used across all
.Net enabled languages.
 The .Net framework class library (FCL) classes are managed classes that provide access to
system services.
 The .Net framework class library (FCL) classes are object oriented and easy to use in
program developments.
 Third-party components can integrate with the classes in the .Net framework.

Common Language Specification (CLS)

 The Common Language Specification (CLS) is one of the specification that describes that
the compiled code of every .Net language should be same (i.e. Common Intermediate
Language (CIL) / MSIL code).
 By following this specification Microsoft design that compilers of every .Net language to
give same compiled code known as Common Intermediate Language (CIL) code.
 Common Language Specification (CLS) ensure complete interoperability among
applications, regardless of the language used to create the application.
 Common Language Specification (CLS) defines a subset of Common Type System (CTS).

KLE’S COLLEGE OF BCA GOKAK Page 9


UNIT 1 C#

Common Type System (CTS)

 This specification describe that the similar data type of every .Net language should be same
in the memory allocation sizes.
 By following this specification they design the datatypes to be allocated same memory
sizes in every language.
 This specification rectifies another problem to provide language interoperability that is
above similar datatype sizes
 Common Type System (CTS) ensure that objects written in different .Net language can
interact with each other.
Garbage Collection (GC)

 The .Net framework provides a new mechanism for releasing unreferenced objects from
the memory (that is we no longer needed that objects in the program), this process is called
Garbage Collection (GC).
 When a program creates an object, the object takes up the memory.
 The program has no more references to that object, the object’s memory becomes
unreachable, but it is not immediately freed.
 The Garbage Collection (GC) checks to see if there are any objects in the heap that are no
longer being used by the application.
 If such objects exit then the memory used by these objects can be reclaimed these
unreferenced objects should be removed from memory then the object new objects you
create can find a place in the heap.
 This releasing of unreferenced objects is happening automatically in .Net languages by the
Garbage Collector (GC).

KLE’S COLLEGE OF BCA GOKAK Page 10


UNIT 1 C#

Base Class Library (BCL)

 This specification describe to define a single library for entire .Net framework to be used
in every .Net language.
 A library is a collection of predefined functionalities or program.
 A library can be called with different name & different language like Header file in C &
C++ language, packages in java language and BCL in .Net framework.
 The BCL contains the predefined function or program which is written or develop by using
a single language know as C#.

Similarities between Java and C#

SI C# Java
No
1 It is an Object Oriented Language It is an Object Oriented Language
2 C# are the descended from C and C++ Java are the descended from C and C++
3 C# compiler generates MSIL code Java compiler generates Byte Code
4 In C# the intermediate code can be run by In java the intermediate code can be run by
interpretation or JIT compilation on an interpretation or JIT compilation on an
appropriate CLR. appropriate JVM.
5 C# supports garbage collection Java supports garbage collection

KLE’S COLLEGE OF BCA GOKAK Page 11


UNIT 1 C#

Difference between C# and C++

SI C++ C#
No
1 C++ is a low-level language C# is a High-Level language
2 It support the multiple inheritance It does not support multiple inheritance
3 In C++ you require to manage memory C# automatically manages memory
manually
4 In C++ after compiling code changed into In C# after compiling code is changed into
machine code (.exe) an intermediate language code (MSIL).

5 C++ used for developed console C# programming used for windows,


applications mobile and console applications
6 For each loop is not supported in C++ For each loop support in C#
7 C++ does not support garbage collection C# support garbage collection
8 C++ does not support bound checking or C# supports bound checking of array
arrays
9 Using this language create a stand-alone Using this language cannot create a stand-
application alone application
10 In C++ you can use pointer anywhere in the In C# only in unsafe mode you can use a
program pointer

KLE’S COLLEGE OF BCA GOKAK Page 12


UNIT 1 C#

Difference between Java and C#

SI C# Java
No
1 C# developed by Microsoft Java developed by sun-microsystem
2 C# founder Anders Hejlsberg Java founder James Gosling
3 In C# uses CLR In java uses JVM
4 C# supports operator overloading of Java does not support operator overloading
multiple operators
5 To import libraries / file uses using To import libraries / file using packages
keyword

Difference between Java & Visual Basic

SI Visual Basic Java


No

1 Visual Basic comes from Microsoft Java comes from sun Microsystem

2 Visual Basic is imperative / procedural Java is entirely an object-oriented language


with weak support for object
3 Visual Basic syntax derives from Algol Java syntax derives from C

KLE’S COLLEGE OF BCA GOKAK Page 13


UNIT 1 C#

Understanding the ‘HELLO WORLD’ application code

using System;
Namespace under
BCL
Keywor
d class
{ demo Class
Name
public static void Main()
Access { Entry Point or Program
Specifier starts
Console.WriteLine(“Hello World”);
from here
Class under
Console.ReadLine();
System
Namespace Method under console class
}

}
Using ReadLine() method To hold our
output/screen in Visual Studio
Closing brace of
main function

Closing brace of class

Note-

In C ----------------------- > Header File (#include<stdio.h>)

In C++ ------------------- >Header File (#include<iostream.h>)

In JAVA ---------------- > import package (same behaves like C and C++ header file)

In C# ------------------- > using System (same behaves like C and C++ header file)

KLE’S COLLEGE OF BCA GOKAK Page 14


UNIT 1 C#

Namespace in C#

 Namespace are the way to organize .Net framework class library into a logical grouping
according to their functionality, usability as well as category they should belong to, or we
can say Namespace are logical grouping of types for the purpose of identification.
 To consume or execute a type or program should be prefix with namespace name for every
time.
 So instead of prefixing with the namespace name every time we can also import that
namespace on top of the program with the help of using keyword.
 If at all a class is defined under a Namespace we can consume that class anywhere only
referring it with its Namespace always.

System ()

 Is a namespace where as namespace is a logical container of types as follows.


o Class
o Structure
o Interface
o Delegates
o Enum

Console ()

 Is a predefined class under Base Class Library (BCL) which is collection of set of members
to perfume input and output operations on a standard input and output devices.
 This class contains a set of static methods like WriteLine(), ReadLine(), Write(), Read()
which can be execute by calling with its class name because those are static method.
 The console class is predefined under a system namespace of Base Class Library (BCL).

KLE’S COLLEGE OF BCA GOKAK Page 15


UNIT 1 C#

Write()

 This method is used to display any message to the user in the output stream.
 After displaying the message blinking cursor remains in the same line.

Ex.

Console.Write(“kle gokak”);

o/p- kle gokak

WriteLine()

 This method is used to display required message to the user on the output stream.
 After displaying the message blinking cursor moves to a new line.

Ex.

Console.WriteLine(“kle gokak”);

o/p- kle gokak

Read()

 Read method reads the single character and convert that character into the ASCII value that
means it returns the value of type integer.

ReadLine()

KLE’S COLLEGE OF BCA GOKAK Page 16


UNIT 1 C#

 This will read an input stream from the console window and return the input string when
user presses the enter key.
 And it convert any type of value to string type we mostly use ReadLine() instead of Read().

Clear()

This method is used to delete the contents of screen and is same as clrscr() in C / C++.

How to import Namespace in program –

ImportDemo.cs Save the program with name ImportDemo.cs

Using System; // namespace

Class ImportDemo // class classname

static void Main() // Entry point

Console.WriteLine(“Hello World”); // Printing message

Console.ReadLine();

The Class Keyword

 Class is a predefined keyword.


 A class is a user defined type like structure which is collection of members.
 A program that define using class or structure will becomes a user defined type.

KLE’S COLLEGE OF BCA GOKAK Page 17


UNIT 1 C#

 In which every predefined data type are already define like classes and structure.

Ex.

Class student

-------- members

The Main() method

 The Main() is an entry point in every program.


 The main method should be defined as a static member in the class by using static keyword
to be execute first under the class without object usage.
 A main method can be defined as a non-value returning method by using void keyword
and also can be defined as value returning method but of integer type only.

Ex.

Static void Main()

The using keyword

 To import namespace in our program using keyword Using .

Comments

KLE’S COLLEGE OF BCA GOKAK Page 18


UNIT 1 C#

 Comments play a very important role in the maintenance of program.


 It is used to readability and understanding of code.
 All program should have information such as implementation details, change history and
tasks performed.

Comments are Two types-

1) Single Line Command


2) Multi Line Command

1. Single Line Command

 It begins with double backslash (//).


 This can also be used to comment out an entire line or part of a line of source code.

2. Multi Line Command

 It begins with single forward slash and star (/*) and end with backward slash and star (*\)
 This can be used for multiple block or multiple line

KLE’S COLLEGE OF BCA GOKAK Page 19


UNIT 1 C#

KLE’S BCA COLLEGE GOKAK Page 20


UNIT 2 C# .NET BASICS

C# Data Types

 In C# programming language, Data Types are used to define a type of data the variable can hold such as integer, float,
string, etc. in our application.
 C# is a Strongly Typed programming language so before we perform any operation on variables, it’s mandatory to
define a variable with the required data type to indicate what type of data that variable can hold in our application.

Syntax of Defining C# Data Types


Following is the syntax of defining data types in c# programming language.

[Data Type] [Variable Name];


[Data Type] [Variable Name] = [Value];
If you observe the above syntax, we added a required data type before the variable name to tell the compiler about what type of
data the variable can hold or which data type the variable belongs to.

[Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.

[Variable Name] - It’s a name of the variable to hold the values in our application.

[Value] - Assigning a required value to the variable.

C# Data Types Example


namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
}
}
}
If you observe above c# data types example, we defined a multiple variables with different data types based on our requirements.

KLE’S BCA COLLEGE GOKAK Page 1


UNIT 2 C# .NET BASICS

Different Data Types in C#


In C# programming language, we have a 3 different type of data types, those are

Type Data Types

Value Data Type int, bool, char, double, float, etc.

Reference Data Type string, class, object, interface, delegate, etc.

Pointer Data Type Pointers.

The following diagram will illustrate more detail about different data types in c# programming language.

C# Value Data Types


In c#, the Value Data Types will directly store the variable value in memory. In c#, the value data types will accept both signed
and unsigned literals.

The following table lists the value data types in c# programming language with memory size and range of values.
Data Type .NET Type Size Range

byte Byte 8 bits 0 to 255

sbyte SByte 8 bits -128 to 127

int Int32 32 bits -2,147,483,648 to 2,147,483,647

uint UInt32 32 bits 0 to 4294967295

short Int16 16 bits -32,768 to 32,767

ushort UInt16 16 bits 0 to 65,535

KLE’S BCA COLLEGE GOKAK Page 2


UNIT 2 C# .NET BASICS

Data Type .NET Type Size Range

long Int64 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

ulong UInt64 64 bits 0 to 18,446,744,073,709,551,615

float Single 32 bits -3.402823e38 to 3.402823e38

double Double 64 bits -1.79769313486232e308 to 1.79769313486232e308

bool Boolean 8 bits True or False

decimal Decimal 128 bits (+ or -)1.0 x 10e-28 to 7.9 x 10e28

DateTime DateTime - 0:00:00am 1/1/01 to 11:59:59pm 12/31/9999

C# Reference Data Types


In c#, the Reference Data Types will contain a memory address of variable value because the reference types won’t store the
variable value directly in memory.

The following table lists the reference data types in c# programming language with memory size and range of values.

Data Type .NET Type Size Range

string String Variable Length 0 to 2 billion Unicode characters

object Object - -

C# Pointer Data Types


In c#, the Pointer Data Types will contain a memory address of the variable value. To get the pointer details we have two
symbols ampersand (&) and asterisk (*) in c# language.

Following is the syntax of declaring the pointer type in c# programming language.

type* test;
Following is the example of defining the pointer type in c# programming language.

int* a;
int* b;
The following table lists the detail about different type pointer symbols available in c# programming language.

Symbol Name Description

& Address Operator It's useful to determine the address of a variable.

* Indirection Operator It's useful to access the value of an address.

KLE’S BCA COLLEGE GOKAK Page 3


UNIT 2 C# .NET BASICS

C# Variables
 Variables are containers for storing data values.
Syntax of C# Variables Declaration
Following is the syntax of declaring and initializing variables in c# programming language.

[Data Type] [Variable Name];


[Data Type] [Variable Name] = [Value];
[Access Specifier] [Data Type] [Variable Name] = [Value];
If you observe the above syntax, we added a required data type before the variable name to tell the compiler about what type of
data the variable can hold or which data type the variable belongs to.

[Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.

[Variable Name] - It’s a name of the variable to hold the values in our application.

[Value] - Assigning a required value to the variable.

[Access Specifier] - It is used to define access permissions for the variable.

Now we will see how to define variables in our c# applications with examples.

C# Variables Declaration Example


Following is the example of using the variables in c# programming language.
using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
Console.WriteLine("Id: " + number);
Console.WriteLine("Name: " + name);
Console.WriteLine("Percentage: " + percentage);
Console.WriteLine("Gender: " + gender);
Console.WriteLine("Verified: " + isVerified);
Console.ReadLine();
}
}
}
If you observe the above c# variables example, we defined multiple variables with different data types and assigned values based
on our requirements.
Output of C# Variables Declaration Example
When you execute the above program by pressing Ctrl + F5 or click on Start option in the menu bar you will get the result like as
shown below.

KLE’S BCA COLLEGE GOKAK Page 4


UNIT 2 C# .NET BASICS

Rules to Declare C# Variables


Before we declare and define variables in c# programming language, we need to follow particular rules.

 You can define a variable name with the combination of alphabets, numbers, and underscore.
 A variable name must always start with either alphabet or underscore but not with numbers.
 While defining the variable, no white space is allowed within the variable name.
 You should not use any reserved keywords such as int, float, char, etc. for a variable name.
 In c#, once the variable is declared with a particular data type, it cannot be re-declared with a new type and we
shouldn’t assign a value that is not compatible with the declared type.
 The following are some valid ways to define the variable names in the c# programming language.
Eg:
int abc;
float a2b;
char _abc;
The following are some of the Invalid ways of defining the variable names in c# programming language.

int a b c;
float 2abc;
char &abc;
double int;
C# Multiple and Multi-Line Variables Declaration
In c#, we can declare and initialize multiple variables of the same data type in a single line by separating with a comma.

Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma in
c# programming language.

int a, b, c;
float x, y, z = 10.5;
While declaring the multiple variables of the same data type, we can arrange them in multiple lines to make it more readable and
the compiler will treat it a single statement until it encounters a semicolon (;).

Following is the simple of defining the multiple variables of the same data type in multiple lines in c# programming language.

int a,
b,
c;
float x,y,
z = 10.5;

C# Variables Assignment
In c#, once we declare and assign a value to the variable that can be assigned to another variable of the same data type.

Following is the example of assigning a value of one variable to another variable of the same type in c# programming language.

int a = 123;
int b = a;
string name = "suresh";
string firstname = name;
In c#, it’s mandatory to assign a value to the variable before we use it otherwise we will get a compile-time error.

In case, if we try to assign a value of string data type to an integer data type or vice versa like as shown below, we will get an
error like “cannot implicitly convert type int to string”.

int a = 123;
string name = a;

KLE’S BCA COLLEGE GOKAK Page 5


UNIT 2 C# .NET BASICS

C# Keywords (Reserved)
In c#, Keywords are the predefined set of reserved words that have special meaning for the compiler. So the keywords in c#
cannot be used as identifiers such as variable name, class name, etc. in our applications.
C# Use Keywords as Variable Names
In case, if you want to use Keywords as variable names (identifiers), then you need to include @ as a prefix for your variable
names. For example, @switch is a valid identifier but the switch is not because it’s a keyword and having a special meaning for
the compiler.

Following is the example of using the reserved keywords as variable names by including @ as a prefix in c# programming
language.

using System;

namespace CsharpExamples
{
public class @class
{
public int age;
}
class Program
{
static void Main(string[] args)
{
@class p1 = new @class();
p1.age = 10;
Console.WriteLine("Age: "+p1.age);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above c# example, we used a class keyword as a variable name (@class) by including @ as a prefix.

When you execute the above program you will get the result as shown below

KLE’S BCA COLLEGE GOKAK Page 6


UNIT 2 C# .NET BASICS

C# Operators (Arithmetic, Relational, Logical, Assignment,


Precedence)
In c#, the Operator is a programming element that specifies what kind of operation needs to perform on operands or variables.
For example, an addition (+) operator in c# is used to perform the sum operation on operands.

In c#, we have a different type of operators available, those are

1. Arithmetic Operators
In c#, Arithmetic Operators are useful to perform basic arithmetic calculations like addition, subtraction, division, etc. based on
our requirements.

For example, we have an integer variables x = 20, y = 10 and if we apply an arithmetic operator + (x + y) to perform an addition
operator, then we will get the result as 30 like as shown below.

int result;
int x = 20, y = 10;
result = (x + y);
Following table lists the different type of operators available in c# arithmetic operators.

Operator Name Description Example (a = 6, b = 3)

+ Addition It adds two operands. a+b=9

- Subtraction It subtracts two operands. a-b=3

* Multiplication It multiplies two operands. a * b = 18

/ Division It divides numerator by de-numerator. a/b=2

% Modulo It returns a remainder as a result. a%b=0


C# Arithmetic Operators Example
Following is the example of using the Arithmetic Operators in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{

KLE’S BCA COLLEGE GOKAK Page 7


UNIT 2 C# .NET BASICS
int result;
int x = 20, y = 10;
result = (x + y);
Console.WriteLine("Addition Operator: " + result);
result = (x - y);
Console.WriteLine("Subtraction Operator: " + result);
result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result);
result = (x / y);
Console.WriteLine("Division Operator: " + result);
result = (x % y);
Console.WriteLine("Modulo Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above code, we used an Arithmetic operators (+, -, *, /, %) to perform different operations on defined operands
based on our requirements.
Output of C# Arithmetic Operators Example
When we execute the above c# program, we will get the result like as shown below.

This is how we can use arithmetic operators in c# programming language to perform the basic arithmetic calculations on
operands based on our requirements.

2. C# Relational Operators with Examples


In c#, Relational Operators are useful to check the relation between two operands like we can determine whether two operand
values equal or not, etc. based on our requirements.

Generally, in c# the relational operators will return true only when the defined operands relationship becomes true otherwise, it
will return false.

For example, we have integer variables a = 10, b = 20 and if we apply a relational operator >= (a >= b), we will get the
result false because the variable “a” contains a value which is less than variable b.

The following table lists the different types of operators available in c# relational operators.

Example (a = 6, b
Operator Name Description = 3)

== Equal to It compares two operands and it returns true if both are the same. a == b (false)

> Greater than It compares whether left operand greater than the right operand or not and returns a > b (true)
true if it is satisfied.

KLE’S BCA COLLEGE GOKAK Page 8


UNIT 2 C# .NET BASICS

Example (a = 6, b
Operator Name Description = 3)

< Less than It compare whether left operand less than right operand or not and return true if it is a < b (false)
satisfied.

>= Greater than or It compares whether left operand greater than or equal to right operand or not and a >= b (true)
Equal to return true if it is satisfied.

<= Less than or Equal It compares whether left operand less than or equal to right operand or not and a <= b (false)
to return true if it is satisfied.

!= Not Equal to It checks whether two operand values equal or not and return true if values are not a != b (true)
equal.

C# Relational Operators Example


Following is the example of using the Relational Operators in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
bool result;
int x = 10, y = 20;
result = (x == y);
Console.WriteLine("Equal to Operator: " + result);
result = (x > y);
Console.WriteLine("Greater than Operator: " + result);
result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result);
result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used different Relational operators (<, >, ==) to perform required operations on defined
operands.
Output of C# Relational Operators Example
When we execute the above c# program, we will get the result like as shown below.

KLE’S BCA COLLEGE GOKAK Page 9


UNIT 2 C# .NET BASICS
This is how we can use the relational operators in c# programming language to check the relationship between defined operands
based on our requirements.
3. C# Logical Operators with Examples
In c#, Logical Operators are useful to perform the logical operation between two operands like AND, OR and NOT based on our
requirements. The Logical Operators will always work with Boolean expressions (true or false) and return Boolean values.

The operands in logical operators must always contain only Boolean values otherwise Logical Operators will throw an error.

The following table lists the different types of operators available in c# logical operators.

Example (a = true, b =
Operator Name Description false)

&& Logical It return true if both operands are non zero. a && b (false)
AND

|| Logical OR It returns true if any one operand becomes a non zero. a || b (true)

! Logical It will return the reverse of a logical state that means if both operands are non zero !(a && b) (true)
NOT then it will return false.
If we use Logical AND, OR operators in c# applications, those will return the result like as shown below for different inputs.

Operand1 Operand2 AND OR

true true true true

true false false true

false true false true

false false false false


If you observe the above table if any one operand value becomes false, then the logical AND operator will return false, the same
way the logical OR operator will return true if any one operand value becomes true.

In case if we use Logical NOT operator in our c# applications, it will return the results like as shown below for different inputs.

Operand NOT

true false

false true
If you observe the above table, the Logical NOT operator will always return the reverse value of operand like if operand
value true, then the Logical NOT operator will return false and vice versa.
4. C# Logical Operators Example
Following is the example of using the Logical Operators in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 15, y = 10;
bool a = true, result;

KLE’S BCA COLLEGE GOKAK Page 10


UNIT 2 C# .NET BASICS
// AND operator
result = (x <= y) && (x > 10);
Console.WriteLine("AND Operator: " + result);
// OR operator
result = (x >= y) || (x < 5);
Console.WriteLine("OR Operator: " + result);
//NOT operator
result = !a;
Console.WriteLine("NOT Operator: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used logical operators (AND, OR, NOT) to perform different operations on defined operands.
Output of C# Logical Operators Example
When we execute the above c# program, we will get the result like as shown below.

This is how we can use logical operators in c# programming language to perform logical operations on defined operands based
on our requirements.
5. C# Bitwise Operators with Examples
In c#, Bitwise Operators will work on bits and these are useful to perform a bit by bit operations such as Bitwise AND (&),
Bitwise OR (|), Bitwise Exclusive OR (^), etc. on operands and we can perform bit-level operations on Boolean and integer data.
Following table lists the different types of operators available in c# bitwise operators.

Example (a =
Operator Name Description 0, b = 1)

& Bitwise AND It compares each bit of the first operand with the corresponding bit of its second a & b (0)
operand. If both bits are 1, then the result bit will be 1 otherwise the result bit will be 0.

| Bitwise OR It compares each bit of the first operand with the corresponding bit of its second a | b (1)
operand. If either of the bit is 1, then the result bit will be 1 otherwise the result bit will
be 0.

^ Bitwise Exclusive It compares each bit of the first operand with the corresponding bit of its second a ^ b (1)
OR (XOR) operand. If one bit is 0 and the other bit is 1, then the result bit will be 1 otherwise the
result bit will be 0.

~ Bitwise It operates on only one operand and it will invert each bit of operand. It will change bit ~(a) (1)
Complement 1 to 0 and vice versa.

<< Bitwise Left Shift) It shifts the number to the left based on the specified number of bits. The zeroes will be b << 2 (100)
added to the least significant bits.

>> Bitwise Right Shift It shifts the number to the right based on the specified number of bits. The zeroes will b >> 2 (001)
be added to the least significant bits.

C# Bitwise Operators Example


KLE’S BCA COLLEGE GOKAK Page 11
UNIT 2 C# .NET BASICS
Following is the example of using the Bitwise Operators in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 5, y = 10, result;
result = x & y;
Console.WriteLine("Bitwise AND: " + result);
result = x | y;
Console.WriteLine("Bitwise OR: " + result);
result = x ^ y;
Console.WriteLine("Bitwise XOR: " + result);
result = ~x;
Console.WriteLine("Bitwise Complement: " + result);
result = x << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
result = x >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above code, we used different bitwise operators (&, |, ^, ~, <<, >>) to perform different operations on defined
operands.
Output of C# Bitwise Operators Example
When we execute the above c# program, we will get the result like as shown below.

This is how we can use bitwise operators in c# programming language to perform bit by bit operations on defined operands based
on our requirements.

C# Assignment Operators with Examples


In c#, Assignment Operators are useful to assign a new value to the operand and these operators will work with only one operand.

For example, we can declare and assign a value to the variable using assignment operator (=) like as shown below.

int a;
a = 10;
If you observe the above sample we defined a variable called “a” and assigned a new value using an assignment operator (=)
based on our requirements.

Following table lists the different types of operators available in c# assignment operators.

KLE’S BCA COLLEGE GOKAK Page 12


UNIT 2 C# .NET BASICS

Operator Name Description Example

= Equal to It is used to assign the values to variables. int a; a = 10

+= Addition Assignment It performs the addition of left and right operands and assigns a result to a += 10 is equals to a
the left operand. = a + 10

-= Subtraction Assignment It performs the subtraction of left and right operands and assigns a result a -= 10 is equals to a =
to the left operand. a - 10

*= Multiplication Assignment It performs the multiplication of left and right operands and assigns a a *= 10 is equals to a
result to the left operand. = a * 10

/= Division Assignment It performs the division of left and right operands and assigns a result to a /= 10 is equals to a =
the left operand. a / 10

%= Modulo Assignment It performs the modulo operation on two operands and assigns a result to a %= 10 is equals to a
the left operand. = a % 10

&= Bitwise AND Assignment It performs the Bitwise AND operation on two operands and assigns a a &= 10 is equals to a
result to the left operand. = a & 10

|= Bitwise OR Assignment It performs the Bitwise OR operation on two operands and assigns a a |= 10 is equals to a =
result to the left operand. a | 10

^= Bitwise Exclusive OR It performs the Bitwise XOR operation on two operands and assigns a a ^= 10 is equals to a
Assignment result to the left operand. = a ^ 10

>>= Right Shift Assignment It moves the left operand bit values to right based on the number of a >>= 2 is equals to a
positions specified by the second operand. = a >> 2

<<= Left Shift Assignment It moves the left operand bit values to left based on the number of a <<= 2 is equals to a
positions specified by the second operand. = a << 2

C# Assignment Operators Example


Following is the example of using assignment Operators in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 20;
x += 10;
Console.WriteLine("Add Assignment: " + x);
x *= 4;
Console.WriteLine("Multiply Assignment: " + x);
x %= 7;
Console.WriteLine("Modulo Assignment: " + x);
x &= 10;
Console.WriteLine("Bitwise And Assignment: " + x);
x ^= 12;
Console.WriteLine("Bitwise XOR Assignment: " + x);
x >>= 3;

KLE’S BCA COLLEGE GOKAK Page 13


UNIT 2 C# .NET BASICS
Console.WriteLine("Right Shift Assignment: " + x);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above example, we defined a variable or operand “x” and assigning new values to that variable by using
assignment operators in c# programming language.
Output of C# Assignment Operators Example
When we execute the above c# program, we will get the result like as shown below.

This is how we can use assignment operators in c# to assign a new values to the variable based on our requirements.
C# Operators Precedence with Examples
In c#, Operators Precedence is useful to define multiple operators in single expression and the evaluation of expression can be
happened based on the priority of operators.

For example, the multiplication operator (*) is having higher precedence than the addition operator (+). So if we use both
multiplication (*) and addition (+) operators in a single expression, first it will evaluate the multiplication part and then the
addition part in expression.

Following is the simple example of defining an expression with operator precedence in c#.

int i = 3 + 4 * 5;
When we execute the above statement, first the multiplication part (4 * 5) will be evaluated. After that, the addition part (3 + 12)
will be executed and i value will become a 23.

As said earlier, multiplication (*) operator is having higher precedence than addition (+) operator so the first multiplication part
will be executed.

The following table lists the different types of operators available in c# relational operators.

Category Operator(s)

Postfix / Prefix ++, --

Unary +, -, !, ~

Multiplicative *, /, %

Additive +, -

Shift <<, >>

Relational <, <=, >, >=

Equality ==, !=

KLE’S BCA COLLEGE GOKAK Page 14


UNIT 2 C# .NET BASICS

Category Operator(s)

Bitwise &, |, ^

Logical &&, ||

Conditional ?:

Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

C# Operator Precedence Example


Following is the example of implementing operator precedence in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 20, y = 5, z = 4;
int result = x / y + z;
Console.WriteLine("Result1: "+result);
bool result2 = z <= y + x;
Console.WriteLine("Result2: "+result2);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe the above example, we implemented operator precedence with multiple operators and the evaluation of
expressions will be done based on the priority of operators in c# programming language.
Output of C# Operators Precedence Example
When we execute the above c# program, we will get the result like as shown below.

This is how we can implement operator precedence in c# programming language based on our requirements.

KLE’S BCA COLLEGE GOKAK Page 15


UNIT 2 C# .NET BASICS

Flow Control and Conditional Statements


 if statement
 if else
 else if
 while
 do while
 switch
 for
 for each
C# if statement
 Use the if statement to specify a block of C# code to be executed if a condition is True.
The if statement has the following general form:
if (expression)
{
statement;
}
Example:
class Program
{
static void Main(string[] args)
{
int x,y;
x= 10;
y=15;
if(x<y)
{
Console.WriteLine("x is less than y");
}
}
}
If else statement
Use the else statement to specify a block of code to be executed if the condition is False.
Syntax:
if (condition)
{
// block of code to be executed if the condition is True
}
Else
{
// block of code to be executed if the condition is False
}
Example:
class Program
{
static void Main(string[] args)
{
int time = 20;
if(time<18)
{

KLE’S BCA COLLEGE GOKAK Page 16


UNIT 2 C# .NET BASICS

Console.WriteLine("Good evening");
}
else
{
Console.WriteLine("Good night");
}
}
}
The else if Statement
Use the else if statement to specify a new condition if the first condition is False.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is True
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is True }
else {
// block of code to be executed if the condition1 is false and condition2 is False }
Example:
class Program
{
static void Main(string[] args)
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} Console.ReadLine();
}
}
The else if Statement
Use the else if statement to specify a new condition if the first condition is False.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is True
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is True }
else {
// block of code to be executed if the condition1 is false and condition2 is False }

Example:

KLE’S BCA COLLEGE GOKAK Page 17


UNIT 2 C# .NET BASICS

class Program
{
static void Main(string[] args)
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
} Console.ReadLine();
}
}
C# While Loop
The while loop loops through a block of code as long as a specified condition is True:
while (condition)
{
// code block to be executed
}
Example:
class Program
{
static void Main(string[] args)
{
{
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
}
}
}
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax:
do {
// code block to be executed
}
while (condition);

Example:
KLE’S BCA COLLEGE GOKAK Page 18
UNIT 2 C# .NET BASICS

class Program
{
static void Main(string[] args)
{
int i = 0;
do
{
Console.WriteLine(i);
i++;
}
while (i < 5);
}
}
}
C# Switch Statements
Use the switch statement to select one of many code blocks to be executed.
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
Syntax:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Example:
using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int x = 20;
switch (x)
{
case 10:
Console.WriteLine("x value is 10");
break;
case 15:
Console.WriteLine("x value is 15");
break;

KLE’S BCA COLLEGE GOKAK Page 19


UNIT 2 C# .NET BASICS

case 20:
Console.WriteLine("x value is 20");
break;
default:
Console.WriteLine("Not Known");
break;
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}}}
For loop
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax :
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
Example:
class Program
{
static void Main(string[] args)
{

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


{
Console.WriteLine(i);
}
}}}
for each loop
There is also a for each loop, which is used exclusively to loop through elements in an array:
foreach (type variableName in arrayName)
{
// code block to be executed
}
Example:
class Program
{
static void Main(string[] args)
{
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
foreach (string i in cars)
{
Console.WriteLine(i);
}
}}

Classes and Objects


KLE’S BCA COLLEGE GOKAK Page 20
UNIT 2 C# .NET BASICS

C# Classes and Objects with Examples


In c#, Classes and Objects are interrelated. The class in c# is nothing but a collection of various data members (fields,
properties, etc.) and member functions. The object in c# is an instance of a class to access the defined properties and methods.
C# Class
In c#, Class is a data structure and it will combine various types of data members such as fields, properties, member functions,
and events into a single unit.
Declaring a Class in C#
In c#, classes are declared by using class keyword. Following is the declaration of class in c# programming language.

public class users {

// Properties, Methods, Events, etc.

}
If you observe the above syntax, we defined a class “users” using class keyword with public access modifier. Here,
the public access specifier will allow the users to create objects for this class and inside of the body class, we can create required
fields, properties, methods and events to use it in our applications.

Now we will see how to create a class in c# programming language with example.
C# Class Example
Following is the example of creating a class in c# programming language with various data members and member functions.

public class Users


{
public int id = 0;
public string name = string.Empty;
public Users()
{
// Constructor Statements
}
public void GetUserDetails(int uid, string uname)
{
id = uid;
uname = name;
Console.WriteLine("Id: {0}, Name: {1}", id, name);
}
public int Designation { get; set; }
public string Location { get; set; }
}
If you observe above c# class example, we defined a class “Users” with various data members and member functions based on
our requirements.

Following is the detailed description of various data members that we used in the above c# class example.

KLE’S BCA COLLEGE GOKAK Page 21


UNIT 2 C# .NET BASICS
If you observe the above image, we used various data members like access modifiers, fields, properties, methods, constructors,
etc. in our c# class based on our requirements.

We will learn more about c# access modifiers, fields, properties, methods, constructors, etc. topics in the next chapters with
examples.
In c#, Object is an instance of a class and that can be used to access the data members and member functions of a class.
Creating Objects in C#
Generally, we can say that objects are the concrete entities of classes. In c#, we can create objects by using a new keyword
followed by the name of the class like as shown below.

Users user = new Users();


If you observe the above example, we created an instance (user) for the class (Users) which we created in the previous section.
Now the instance “user” is a reference to an object that is based on Users. By using the object name “user” we can access all the
data members and member functions of Users class.
C# Objects Example
Following is the example of creating objects in c# programming language.

using System;

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
Users user = new Users("Suresh Dasari", 30);
user.GetUserDetails();
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
public class Users
{
public string Name { get; set; }
public int Age { get; set; }
public Users(string name, int age)
{
Name = name;
Age = age;
}
public void GetUserDetails()
{
Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
}
}
}
If you observe above example, we created a new class called “Users” with a required data members and member functions. To
access Users class methods and properties, we created an object (user) for Users class and performing required operations.

When we execute the above c# program, we will get the result as shown below.

C# Access Modifiers (Public, Private, Protected, Internal,Protectedinternal)


KLE’S BCA COLLEGE GOKAK Page 22
UNIT 2 C# .NET BASICS
In c#, Access Modifiers are the keywords which are used to define an accessibility level for all types and type members.

By specifying an access level for all types and type members, we can control whether they can be accessed in other classes or in
current assembly or in other assemblies based on our requirements.

The following are the different types of access modifiers available in c# programming language.

1. Public
2. Private
3. Protected
4. Internal
5. Protected internal
By using these four access modifiers, we can specify a following six levels of accessibility for all types and type members based
on our requirements.

Access Modifier Description

public It is used to specifies that access is not restricted.

private It is used to specifies that access is limited to the containing type.

protected It is used to specifies that access is limited to the containing type or types derived from the
containing class.

internal It is used to specifies that access is limited to the current assembly.

protected It is used to specifies that access is limited to the current assembly or types derived from the
internal containing class.
Generally, in c# only one access modifier is allowed to use with any member or type, except when we use protected
internal or private protected combinations.

In c#, we are not allowed to use any access modifiers on namespaces, because the namespaces have no access restrictions.

Only certain access modifiers are allowed to specify based on the context in which a member declaration occurs. In case, if we
didn’t mention any access modifiers during member declaration, then the default access modifiers will be used depending on the
member declaration context.

For example, the top-level types which are not nested in any other type can only have public or internal accessibility. The
default accessibility for top-level types is internal.
C# Public Access Modifier
In c#, the public modifier is used to specify that access is not restricted, so the defined type or member can be accessed by any
other code in current assembly or another assembly that references it.

Following is the example of defining members with a public modifier in c# programming language.

using System;

namespace Tutlane
{
class User
{
public string Name;
public string Location;
public int Age;
public void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}

KLE’S BCA COLLEGE GOKAK Page 23


UNIT 2 C# .NET BASICS
class Program
{
static void Main(string[] args)
{
User u = new User();
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we defined a User class with required variables and method using public access modifier and
trying to access those variables and method in another class with an object reference of User class.

When you execute the above c# program, you will get the result as shown below.

If you observe the above result, we are able to access the variables and methods of User class in another class because of
specifying with public specifiers based on our requirements.

As discussed, the public access specifier will make all the defined members or types available to all the types in our application.
C# Private Access Modifier
In c#, the private modifier is used to specify that access is limited to the containing type so the defined type or member can only
be accessed by the code in the same class or structure.

Following is the example of defining members with a private modifier in c# programming language.

using System;

namespace Tutlane
{
class User
{
private string Name;
private string Location;
private int Age;
private void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
// Complier Error
// These are inaccessible due to private specifier

KLE’S BCA COLLEGE GOKAK Page 24


UNIT 2 C# .NET BASICS
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we defined a User class with required variables and method using private access modifier and
trying to access those variables and method in another class with an object reference of User class.

When you execute the above c# program, you will get compile-time errors like as shown below.

If you observe the above result, we are getting compile-time errors because the private modifier members of
the User class referred in another class.

As discussed, the private modifier type or member can be accessed only by code in the same class or structure.
C# Protected Access Modifier
In c#, protected modifier is used to specify that access is limited to the containing type or types derived from the
containing class so the type or member can only be accessed by code in the same class or in a derived class.

Following is the example of defining members with a protected modifier in c# programming language.

using System;

namespace Tutlane
{
class User
{
protected string Name;
protected string Location;
protected int Age;
protected void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
// Complier Error
// These are inaccessible due to protected specifier
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}

KLE’S BCA COLLEGE GOKAK Page 25


UNIT 2 C# .NET BASICS
}
If you observe above example, we defined a User class with required variables and method using protected access modifier and
trying to access those variables and method in another class with an object reference of User class.

When you execute the above c# program, you will get compile-time errors like as shown below.

If you observe the above result, we are getting compile-time errors because the protected modifier members of
the User class referred in another class.

As discussed, the protected members of a base class can be accessible in the derived class, only when access occurs through the
derived class type.

Following is the example of accessing a base class protected members in derived class through derived class type.

using System;

namespace Tutlane
{
class User
{
protected string Name;
protected string Location;
protected int Age;
protected void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}
class Program : User
{
static void Main(string[] args)
{
User u = new User();
Program p = new Program();
// Complier Error
// protected members can only accessible with derived classes
//u.Name = "Suresh Dasari";
p.Name = "Suresh Dasari";
p.Location = "Hyderabad";
p.Age = 32;
p.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we are accessing base class (User) protected members using the reference of
derived class (Program) and if we uncomment the commented code we will get a compile time error because we are trying to
access protected members with base class (User) reference instead of derived class (Program).

When you execute the above c# program, you will get the result as shown below.

KLE’S BCA COLLEGE GOKAK Page 26


UNIT 2 C# .NET BASICS

This is how you can use protected modifiers in our c# applications to limit access of type or member in the same class or derived
class based on our requirements.

In c#, the struct members cannot be protected because the struct cannot be inherited.
C# Internal Access Modifier
In c#, the internal modifier is used to specify that access is limited to current assembly so the type or member can be accessed by
any code in the same assembly, but not from another assembly.

Following is the example of defining the members with an internal modifier in c# programming language.

using System;

namespace Tutlane
{
class User
{
internal string Name;
internal string Location;
internal int Age;
internal void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
u.Name = "Suresh Dasari";
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we defined a User class with required variables and method using internal access modifier and
trying to access those variables and method in another class with an object reference of User class.

When you execute the above c# program, you will get the result as shown below.

KLE’S BCA COLLEGE GOKAK Page 27


UNIT 2 C# .NET BASICS

If you observe the above result, we are able to access the variables and methods of User class in another class because of
specifying an internal specifier based on our requirements.

As discussed, in c# the internal type or members are accessible within the files of the same assembly.
C# Protected Internal Access Modifier
In c#, the protected internal modifier is used to specify that access is limited to the current assembly or types derived from the
containing class, so the type or member can be accessed by any code in the same assembly or by any derived class in another
assembly.

Following is the example of defining members with a protected internal modifier in c# programming language.

using System;

namespace Tutlane
{
class User
{
protected internal string Name;
protected internal string Location;
protected internal int Age;
protected internal void GetUserDetails()
{
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
Console.WriteLine("Age: {0}", Age);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
u.Name = "Suresh Dasari";
u.Name = "Suresh Dasari";
u.Location = "Hyderabad";
u.Age = 32;
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we defined a User class with required variables and method using protected internal access
modifier and trying to access those variables and method in another class with an object reference of User class.

When you execute the above c# program, we will get the result as shown below.

KLE’S BCA COLLEGE GOKAK Page 28


UNIT 2 C# .NET BASICS

If you observe the above result, we are able to access the variables and methods of User class in another class because of
specifying an internal specifier based on our requirements.

As discussed, in c# the protected internal type or members are accessible from the current assembly or from the types that are
derived from the containing class in another assembly.
C# Properties (GET, SET)
In c#, Property is an extension of the class variable and it provides a mechanism to read, write or change the value of the
class variable without affecting the external way of accessing it in our applications.

In c#, properties can contain one or two code blocks called accessors and those are called a get accessor and set accessor. By
using get and set accessors, we can change the internal implementation of class variables and expose it without effecting the
external way of accessing it based on our requirements.

Generally, in object-oriented programming languages like c# you need to define fields as private, and then use properties to
access their values in a public way with get and set accessors.

Following is the syntax of defining a property with get and set accessor in c# programming language.

<access_modifier> <return_type> <property_name>


{
get
{
// return property value
}
set
{
// set a new value
}
}
If you observe the above syntax, we used an access modifier and return type to define a property along
with get and set accessors to make required modifications to the class variables based on our requirements.

Here, the get accessor code block will be executed whenever the property is read and the code block of set accessor will be
executed whenever the property is assigned to a new value.

In c#, the properties are categorized as three types, those are.

Type Description

Read-Write A property which contains a both get and set accessors, then we will call it as read-write property.

Read-Only A property which contains only get accessor, then we will call it as a read-only property.

Write-Only A property which contains only set accessor, then we will call it as write-only property.
In c#, Properties won’t accept any parameters and we should not pass a property as a ref or out parameter in our application.

Following is the simple example of defining a private variable and a property in c# programming language.

class User
{
private string name;

KLE’S BCA COLLEGE GOKAK Page 29


UNIT 2 C# .NET BASICS
public string Name
{
get { return name; }
set { name = value; }
}
}
If you observe the above example, we defined a property called “Name” and we used a get accessor to return a property value
and set accessors to set a new value. Here, the value keyword in set accessor is used to define a value that is being assigned
by set accessor.

In c#, the get accessor needs to be used only to return the field value or to compute it and return it but we should not use it for
changing the state of an object.

As discussed, we can extend the behavior of class variables using properties get and set accessors. Following is the example of
extending the behavior of private variable in property using get and set accessors in c# programming language.

class User
{
private string name = "Suresh Dasari";
public string Name
{
get
{
return name.ToUpper();
}
set
{
if (value == "Suresh")
name = value;
}
}
}
If you observe the above example, we are extending the behavior of private variable name using a property
called Name with get and set accessors by performing some validations like to make sure Name value equals to only “Suresh”
using set accessor and converting property text to uppercase with get accessor.

Here the field “name” is marked as private so if you want to make any changes to this field then we can do it only by calling the
property (Name).

In c# properties, the get accessor will be invoked while reading the value of a property and when we assign a new value to the
property, then the set accessor will be invoked by using an argument that provides the new value.

Following is the example of invoking get and set accessors of properties in c# programming language.

User u = new User();


u.Name = "Rohini"; // set accessor will invoke
Console.WriteLine(u.Name); // get accessor will invoke
In the above example, when we assign a new value to the property, then the set accessor will be invoked and the get accessor will
be invoked when we try to read the value from property
C# Static Class with Examples
In c#, a static class can be created by using static modifier and the static class can contain only static members.

Generally, the static class is same as non-static class, but the only difference is the static class cannot be instantiated. Suppose if
we apply static modifier to a class, then we should not use the new keyword to create a variable of the class type.

Another difference is the static class will contain only static members, but the non-static class can contain both static and non-
static members.
C# Static Class Syntax
In c#, we can create a static class by applying static keyword to the class like as shown below.

static class sample

KLE’S BCA COLLEGE GOKAK Page 30


UNIT 2 C# .NET BASICS
{
//static data members
//static methods
}
If you observe the above syntax, to create a static class called “sample”, we applied static keyword to the class type. The
methods and data members that we are going to implement in the sample class must be static.

In c#, we can access members of a static class directly with the class name. For example, we have a static class called “User”
with a method “Details()” that we can access like User.Details().
C# Static Class Example
Following is the example of defining a static class to access data members and member functions without creating an instance of
the class in c# programming language.

using System;

namespace Tutlane
{
static class User
{
// Static Variables
public static string name;
public static string location;
public static int age;
// Static Method
public static void Details()
{
Console.WriteLine("Static Method");
}
}
class Program
{
static void Main(string[] args)
{
User.name = "Suresh Dasari";
User.location = "Hyderabad";
User.age = 32;
Console.WriteLine("Name: {0}", User.name);
Console.WriteLine("Location: {0}", User.location);
Console.WriteLine("Age: {0}", User.age);
User.Details();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we are accessing static class members and functions directly with the class name because we
cannot instantiate the static class.

When you execute the above c# program, you will get the result like ass shown below.

KLE’S BCA COLLEGE GOKAK Page 31


UNIT 2 C# .NET BASICS

This is how we can create a static class and use it in our c# applications based on our requirements.
C# Static Class Features
Following are the main features of static class in c# programming language.

 The static class in c# will contain only static members.


 In c#, the static classes cannot be instantiated.
 C# static classes are sealed, therefore it cannot be inherited.
 The static classes in c# will not contain instance constructors.
 As discussed in the previous article static keyword in c#, we can use static members in non-static classes such as
normal classes. For normal classes, you can create an instance of class using the new keyword to access non-static
members and functions but it cannot access the static members and functions.

Constructors
C# Constructors with Examples
In c#, Constructor is a method which will invoke automatically whenever an instance of class or struct is created. The
constructor will have the same name as the class or struct and it useful to initialize and set default values for the data members of
the new object.

In case, if we create a class without having any constructor, then the compiler will automatically create a one default constructor
for that class. So, there is always one constructor that will exist in every class.

In c#, a class can contain more than one constructor with different types of arguments and the constructors will never return
anything, so we don’t need to use any return type, not even void while defining the constructor method in the class.
C# Constructor Syntax
The constructor is a method and it won’t contain any return type. If you want to create a constructor in c#, then you need to
create a method with the class name.

Following is the syntax of creating a constructor in c# programming language.

public class User


{
// Constructor
public User()
{
// Your Custom Code
}
}
If you observe the above syntax, we created a class called “User” and a method whose name is same as the class name. Here the
method User() will become a constructor of our class.
C# Constructor Types
In c#, we have a different type of constructors available, those are

 Default Constructor
 Parameterized Constructor
 Copy Constructor
 Static Constructor
 Private Constructor
Now we will learn about each constructor in a detailed manner with examples in c# programming language.
C# Default Constructor
In c#, if we create a constructor without having any parameters, then we will call it as default constructor and every instance of
the class will be initialized without any parameter values.

Following is the example of defining the default constructor in c# programming language.

using System;

namespace Tutlane

KLE’S BCA COLLEGE GOKAK Page 32


UNIT 2 C# .NET BASICS
{
class User
{
public string name, location;
// Default Constructor
public User()
{
name = "Suresh Dasari";
location = "Hyderabad";
}
}
class Program
{
static void Main(string[] args)
{
// The constructor will be called automatically once the instance of class created
User user = new User();
Console.WriteLine(user.name);
Console.WriteLine(user.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created a class called “User” and the constructor method “User()” without having any
parameters. When we create an instance of our class (User), then automatically our constructor method will be called.

When you execute the above c# program, you will get the result as shown below.

If you observe the above result, our constructor method has called automatically and initialized the parameter values after
creating an instance of our class.
C# Parameterized Constructor
In c#, if we create a constructor with at least one parameter, then we will call it as a parameterized constructor and every
instance of the class will be initialized with parameter values.

Following is the example of defining the parameterized constructor in c# programming language.

using System;

namespace Tutlane
{
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}

KLE’S BCA COLLEGE GOKAK Page 33


UNIT 2 C# .NET BASICS
class Program
{
static void Main(string[] args)
{
// The constructor will be called automatically once the instance of class created
User user = new User("Suresh Dasari", "Hyderabad");
Console.WriteLine(user.name);
Console.WriteLine(user.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created a class called “User” and the constructor method “User(string, string)” with
parameters. When we create an instance of our class (User) with required parameters, then automatically our constructor method
will be called.

When you execute the above c# program, you will get the result like as shown below.

If you observe the above result, our constructor method has called automatically and initialized the parameter values after
creating an instance of our class with the required parameters.

In the next chapters, you will learn about copy constructor, static constructor and private constructor in c# programming language
with examples.
C# Copy Constructor with Examples
In c#, Copy Constructor is a parameterized constructor that contains a parameter of the same class type. The copy constructor in
c# is useful whenever we want to initialize a new instance to the values of an existing instance.

In simple words, we can say copy constructor is a constructor that copies the data of one object into another object. Generally, c#
won’t provide a copy constructor for objects but we can implement ourselves based on our requirements.
C# Copy Constructor Syntax
Following is the syntax of defining a copy constructor in c# programming language.

class User
{
// Parameterized Constructor
public User(string a, string b)
{
// your code
}
// Copy Constructor
public User(User user)
{
// your code
}
}
If you observe the above syntax, we created a copy constructor with a parameter of the same class type and it helps us to initialize
a new instance to the values of an existing instance.

KLE’S BCA COLLEGE GOKAK Page 34


UNIT 2 C# .NET BASICS

C# Copy Constructor Example


Following is the example of creating a copy constructor to initialize a new instance to the values of an existing instance in c#
programming language.

using System;

namespace Tutlane
{
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
// Copy Constructor
public User(User user)
{
name = user.name;
location = user.location;
}
}
class Program
{
static void Main(string[] args)
{
// User object with Parameterized constructor
User user = new User("Suresh Dasari", "Hyderabad");
// Another User object (user1) by copying user details
User user1 = new User(user);
user1.name = "Rohini Alavala";
user1.location = "Guntur";
Console.WriteLine(user.name + ", " + user.location);
Console.WriteLine(user1.name + ", " + user1.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created an instance of copy constructor (user1) and using an instance of user object as a
parameter type. So the properties of user object will be send to user1 object and we are changing the property values
of user1 object but those will not effect the user object property values.

When you execute the above c# program, you will get the result as shown below.

If you observe the above result, we initialized a new instance to the values of an existing instance but those changes not effected
the existing instance values.

KLE’S BCA COLLEGE GOKAK Page 35


UNIT 2 C# .NET BASICS

C# Static Constructor with Examples


In c#, Static Constructor is useful to perform a particular action only once throughout the application. If we declare
a constructor as static, then it will be invoked only once irrespective of the number of class instances and it will be called
automatically before the first instance is created.

Generally, in c# the static constructor will not accept any access modifiers and parameters. In simple words, we can say it’s
parameter less.

The following are the properties of static constructor in c# programming language.

 Static constructor in c# won’t accept any parameters and access modifiers.


 The static constructor will invoke automatically, whenever we create the first instance of a class.
 The static constructor will be invoked by CLR so we don’t have a control on static constructor execution order in c#.
 In c#, only one static constructor is allowed to create.
 C# Static Constructor Syntax
 Following is the syntax of defining a static constructor in c# programming language.

class User
{
// Static Constructor
static User()
{
// Your Custom Code
}
}
If you observe the above syntax, we created a static constructor without having any parameters and access specifiers.
C# Static Constructor Example
Following is the example of creating a static constructor in c# programming language to invoke the particular action only once
throughout the program.

using System;

namespace Tutlane
{
class User
{
// Static Constructor
static User()
{
Console.WriteLine("I am Static Constructor");
}
// Default Constructor
public User()
{
Console.WriteLine("I am Default Constructor");
}
}
class Program
{
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for first instance
User user = new User();
// Only Default constructor will invoke
User user1 = new User();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

KLE’S BCA COLLEGE GOKAK Page 36


UNIT 2 C# .NET BASICS
If you observe above example, we created a static constructor and default constructor. Here the static constructor will be
invoked only once for the first instance of class.

When you execute the above c# program, we will get the result as shown below.

If you observe the above result, for the first instance of class both static and default constructors execute and for the second
instance of class only default constructor has executed.

C# Private Constructor with Examples


In c#, Private Constructor is a special instance constructor and it is useful in classes that contain only static members. If a class
contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance
for that particular class except nested classes.
C# Private Constructor Syntax
Following is the syntax of defining a private constructor in c# programming language.

class User
{
// Private Constructor
private User()
{
// Your Custom Code
}
}
If you observe the above syntax, we created a private constructor without having any parameters that mean it will prevent an
automatic generation of default constructor. In case, if we didn’t use any access modifier to define constructor, then by default it
will treat it as a private.
C# Private Constructor Example
Following is the example of creating a private constructor in c# programming language to prevent other classes to create an
instance of a particular class.

using System;

namespace Tutlane
{
class User
{
// private Constructor
private User()
{
Console.WriteLine("I am Private Constructor");
}
public static string name, location;
// Default Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}

KLE’S BCA COLLEGE GOKAK Page 37


UNIT 2 C# .NET BASICS
class Program
{
static void Main(string[] args)
{
// The following comment line will throw an error because constructor is inaccessible
//User user = new User();

// Only Default constructor with parameters will invoke


User user1 = new User("Suresh Dasari", "Hyderabad");
Console.WriteLine(User.name + ", " + User.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
If you observe above example, we created a class with private constructor and default constructor with parameters. If you
uncomment the commented line (User user = new User();), then it will throw an error because the constructor is a private so it
won’t allow you to create an instance for that class.

Here we are accessing class properties directly with the class name because those are static properties so it won’t allow you to
access the instance name.

When you execute the above c# program, you will get the result as shown below.

C# Destructor with Examples


In c#, Destructor is a special method of a class and it is used in a class to destroy the object or instances of classes. The
destructor in c# will invoke automatically whenever the class instances become unreachable.

Following are the properties of destructor in c# programming language.

 In c#, destructors can be used only in classes and a class can contain only one destructor.
 The destructor in class can be represented by using tilde (~) operator
 The destructor in c# won’t accept any parameters and access modifiers.
 The destructor will invoke automatically, whenever an instance of a class is no longer needed.
 The destructor automatically invoked by garbage collector whenever the class objects that are no longer needed in the
application.

C# Destructor Syntax
Following is the syntax of defining a destructor in c# programming language.

class User
{
// Destructor
~User()
{
// your code
}
}
If you observe the above syntax, we created a destructor with the same class name using the tilde (~) operator. Here, you need to
remember that the destructor name must always same as class name in c# programming language.

KLE’S BCA COLLEGE GOKAK Page 38


UNIT 2 C# .NET BASICS

C# Destructor Example
Following is the example of using destructor in c# programming language to destruct the unused objects of a class.

using System;

namespace Tutlane
{
class User
{
public User()
{
Console.WriteLine("An Instance of class created");
}
// Destructor
~User()
{
Console.WriteLine("An Instance of class destroyed");
}
}
class Program
{
static void Main(string[] args)
{
Details();
GC.Collect();
Console.ReadLine();
}
public static void Details()
{
// Created instance of the class
User user = new User();
}
}
}
If you observe the above example, we created a class with a default constructor and destructor. Here we created an instance of
class “User” in Details() method and whenever the Details function execution is done, then the garbage collector (GC)
automatically will invoke a destructor in User class to clear the object of a class.

C# Method Overloading
In c#, Method Overloading means defining multiple methods with the same name but with different parameters. By
using Method Overloading, we can perform different tasks with the same method name by passing different parameters.

Suppose, if we want to overload a method in c#, then we need to define another method with the same name but with different
signatures. In c#, the Method Overloading is also called as compile time polymorphism or early binding.

Following is the code snippet of implementing a method overloading in c# programming language.

public class Calculate


{
public void AddNumbers(int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void AddNumbers(int a, int b, int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
If you observe above “Calculate” class, we defined a two methods with same name (AddNumbers) but with different input
parameters to achieve method overloading in c#.

KLE’S BCA COLLEGE GOKAK Page 39


UNIT 2 C# .NET BASICS

C# Method Overloading Example


Following is the example of implementing a method overloading in c# programming language.

using System;

namespace Tutlane
{
public class Calculate
{
public void AddNumbers(int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void AddNumbers(int a, int b, int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new Calculate();
c.AddNumbers(1, 2);
c.AddNumbers(1, 2, 3);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
When you execute above c# program, you will get the result like as shown below.

C# Delegates
In c#, the delegate is a type that defines a method signature and it is useful to hold the reference of one or more methods which
are having the same signatures.

By using delegates, you can invoke the methods and send methods as an argument to other methods.

In c#, the delegate is a reference type and it’s type-safe and secure. The delegates are similar to function pointers in c++.
C# Delegate Declaration Syntax
In c#, the declaration of delegate will be same as method signature but the only difference is we will use a delegate keyword to
define delegates.

Following is the syntax of defining a delegate using delegate keyword in c# programming language.

<access_modifier> delegate <return_type> <delegate_name>(<parameters>)


Following is the example of declaring a delegate using delegate keyword in c#.

public delegate void UserDetails(string name);


If you observe the above example, the declaration of a delegate is same as method declaration with required parameter types and
return value.

KLE’S BCA COLLEGE GOKAK Page 40


UNIT 2 C# .NET BASICS
The above defined method “UserDetails” can be pointed to any other method which is having the same parameters and return
type.

In c#, the delegates must be instantiated with a method or an expression that has the same return type and parameters. We can
invoke a method through the delegate instance.
C# Delegate Example
Following is the example of declaring and using a delegate in c# programming language.

using System;

namespace Tutlane
{
// Declare Delegate
public delegate void SampleDelegate(int a, int b);
class MathOperations
{
public void Add(int a, int b)
{
Console.WriteLine("Add Result: {0}", a + b);
}
public void Subtract(int x, int y)
{
Console.WriteLine("Subtract Result: {0}", x - y);
}
}
class Program
{

static void Main(string[] args)


{
Console.WriteLine("****Delegate Example****");
MathOperations m = new MathOperations();
// Instantiate delegate with add method
SampleDelegate dlgt = m.Add;
dlgt(10, 90);
// Instantiate delegate with subtract method
dlgt = m.Subtract;
dlgt(10, 90);
Console.ReadLine();
}
}
}
If you observe above example, we created a delegate called “SampleDelegate” and the delegate has been instantiated by using
defined methods.

When you execute the above c# program, you will get the result as shown below.

This is how we can use delegates in our applications to call all the methods which are having the same signatures with a single
object.
In c#, you can invoke the delegates same as method or by using the Invoke method like as shown below.
SampleDelegate dlgt = m.Add;
dlgt(10, 90);
// or
dlgt.Invoke(10, 90);

KLE’S BCA COLLEGE GOKAK Page 41


UNIT 2 C# .NET BASICS

C# Delegate Types
In c#, we have a two different type of delegates available, those are

1. Single cast Delegates


2. Multicast Delegates
1. C# Single Cast Delegates
In c#, a delegate which points to a single method is called a single cast delegate and it is used to hold the reference of a single
method like as explained in the above example.
2. C# Multicast Delegates
In c#, a delegate that points to multiple methods is called a multicast delegate and it is used to hold the reference of multiple
methods with a single delegate.

By using "+" operator, we can add the multiple method references to the delegate object. Same way, by using "-" operator we can
remove the method references from the delegate object.

In c#, Multicast delegates will work with only the methods that are having void as return type. In case, if we want to create a
multicast delegate with the return type, then we will get a return type of the last method in the invoking list.
C# Multicast Delegate Example
Following is the example of implementing a multicast delegate to hold the reference of multiple methods with "+" operator in c#
programming language.

using System;

namespace Tutlane
{
// Declare Delegate
public delegate void SampleDelegate(int a, int b);
class MathOperations
{
public void Add(int a, int b)
{
Console.WriteLine("Add Result: {0}", a + b);
}
public void Subtract(int x, int y)
{
Console.WriteLine("Subtract Result: {0}", x - y);
}
public void Multiply(int x, int y)
{
Console.WriteLine("Multiply Result: {0}", x * y);
}
}
class Program
{

static void Main(string[] args)


{
Console.WriteLine("****Delegate Example****");
MathOperations m = new MathOperations();
// Instantiate delegate with add method
SampleDelegate dlgt = m.Add;
dlgt += m.Subtract;
dlgt += m.Multiply;
dlgt(10, 90);
Console.ReadLine();
}
}
}

KLE’S BCA COLLEGE GOKAK Page 42


UNIT 2 C# .NET BASICS
If you observe above example, we created a delegate called “SampleDelegate” and holding the reference of multiple methods
using "+" operator. Now, our delegate become a multicast delegate and invoking a dlgt instance will invoke all the methods
sequentially.

When you execute the above c# program, you will get the result like as shown below.

This is how we can use multicast delegates to hold the reference of multiple methods based on our requirements.
C# | Operator Overloading
The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or
structures is known as operator overloading.
In C#, a special function called operator function is used for overloading purpose. These special function or method must be
public and static.
Syntax:
public static return_type operator op (argument list)
Eg:
public static int operator -(int a)
These binary operators take one operand and can be overloaded.
+, -, *, /, %
These operators cannot be overloaded.
=, ., ?:, ->

Example:
using System;
class Complex
{
private int x;
private int y;
public Complex()
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0} {1}", x, y);
}
public static Complex operator +(Complex c1, Complex c2)
{
Complex temp = new Complex();
temp.x = c1.x + c2.x;
temp.y = c1.y + c2.y;
return temp;
}
}
class MyClient
{
public static void Main()
{

KLE’S BCA COLLEGE GOKAK Page 43


UNIT 2 C# .NET BASICS
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20, 30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}

KLE’S BCA COLLEGE GOKAK Page 44


UNIT
3

Inheritance:

In c#, Inheritance is a one of the primary concept of object oriented programming


(OOP) and it is used to inherit the properties from one class (base) to another (child)
class.

In c# inheritance, the class whose members are inherited is called a base (parent) class
and the class that inherits the members of base (parent) class is called a derived (child)
class.

<access_modifier> class <base_class_name>


{
// Base class Implementation
}

<access_modifier> class <derived_class_name> : <base_class_name>


{
// Derived class implementation
}

If you observe above syntax, we are inheriting the properties of base class into child
class to improve the code reusability.

Example.

using System;

namespace Tutlane
{
public class User
{
public string Name;
private string Location;
public User()
{
Console.WriteLine("Base Class Constructor");
}
public void GetUserInfo(string loc)
{
Location = loc;
Console.WriteLine("Name: {0}", Name);
Console.WriteLine("Location: {0}", Location);
}
}
public class Details : User
{
public int Age;
public Details()
{
Console.WriteLine("Child Class Constructor");
}
public void GetAge()
{
Console.WriteLine("Age: {0}", Age);
}
}
class Program
{
static void Main(string[] args)
{
Details d = new Details();
d.Name = "Suresh Dasari";
// Compile Time Error
//d.Location = "Hyderabad";
d.Age = 32;
d.GetUserInfo("Hyderabad");
d.GetAge();
Console.WriteLine("\nPress Any Key to Exit..");
Console.ReadLine();
}
}
}

If you observe above example, we defined a base class called “User” and inheriting all
the properties of User class into a derived class called “Details” and we are accessing
all the members of User class with an instance of Details class.

If we uncomment the commented code, we will get a compile time error because the
Location property in User class is defined with a private access modifier and the private
members can be accessed only within the class.
C# Multi Level Inheritance: Generally, c# supports only single inheritance
that means a class can only inherit from one base class. However, in c# the inheritance
is transitive and it allows you to define a hierarchical inheritance for a set of types and it
is called a multi-level inheritance.

For example, suppose if class C is derived from class B, and class B is derived from
class A, then the class C inherits the members declared in both class B and class A.

Example

1. using System;
2. public class Animal
3. {
4. public void eat() { Console.WriteLine("Eating..."); }
5. }
6. public class Dog: Animal
7. {
8. public void bark() { Console.WriteLine("Barking..."); }
9. }
10. public class BabyDog : Dog
11. {
12. public void weep() { Console.WriteLine("Weeping..."); }
13. }
14. class TestInheritance2{
15. public static void Main(string[] args)
16. {
17. BabyDog d1 = new BabyDog();
18. d1.eat();
19. d1.bark();
20. d1.weep();
21. }
22. }

OUTPUT:

Eating...
Barking...
Weeping...
Base Keyword: In c#, base keyword is used to access a base class members such
as properties, methods, etc. in derived class.

C# Call Base Class Constructor from Derived Class


As discussed, we can call a base class constructor from derived class using
base
keyword.

Example:

using System;

namespace Tutlane
{
// Base Class
public class BClass
{
public BClass()
{
Console.WriteLine("Welcome to Tutlane");
}
public BClass(string a, string b)
{
Console.WriteLine("Name: {0}", a);
Console.WriteLine("Location: {0}", b);
}
}
// Derived Class
public class DClass : BClass
{
// This constructor will call default constructor
public DClass(): base()
{
}

// This constructor will call parameterized constructor


public DClass(string x, string y): base(x, y)
{
}
}
class Program
{
static void Main(string[] args)
{
DClass d = new DClass();
DClass d1 = new DClass("Suresh Dasari", "Hyderabad");
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe above example, we are calling base class (BClass) constructors in
derived class (DClass) using base keyword.

C# Method Overriding:
If derived class defines same method as defined in its base class, it is known as method
overriding in C#. It is used to achieve runtime polymorphism. It enables you to provide specific
implementation of the method which is already provided by its base class.

To perform method overriding in C#, you need to use virtual keyword with base class method
and override keyword with derived class method.

Let's see a simple example of method overriding in C#. In this example, we are overriding
the eat() method by the help of override keyword.

Example:

1. using System;
2. public class Animal
3. {
4. public virtual void eat()
5. {
6. Console.WriteLine("Eating...");
7. }
8. }
9. public class Dog: Animal
10. {
11. public override void eat()
12. {
13. Console.WriteLine("Eating bread...");
14. }
15. }
16. public class TestOverriding
17. {
18. public static void Main()
19. {
20. Dog d = new Dog();
21. d.eat();
22. }
23. }

Output:

Eating bread..

Non-Inheritable Classes:

Sealed Class: C# sealed keyword applies restrictions on the class and method. If you
create a sealed class, it cannot be derived. If you create a sealed method, it cannot be
overridden.

Abstract classes:
In c#, abstract is a keyword and it is useful to define a classes and class members that
are needs to be implemented or overridden in a derived class.

In c#, we can use abstract modifier with classes, methods, properties, events and
indexers based on our requirements. The members which we defined as abstract or
included in an abstract class those must be implemented by a classes that derive from
an abstract class.
In c#, abstract class is a class which is declared with an abstract modifier. If we define a class
with abstract modifier, then that class is intended only to be used as a base class for other
classes.

The abstract class cannot be instantiated and it can contain both abstract and non-abstract
members. The class that is derived from abstract class must implement all the inherited abstract
methods and accessors.

Example:
using System;

namespace Tutlane
{
abstract class Info
{
abstract public void GetDetails(string x, string y, int z);
}
class User : Info
{
public override void GetDetails(string a, string b, int c)
{
Console.WriteLine("Name: {0}", a);
Console.WriteLine("Location: {0}", b);
Console.WriteLine("Age: {0}", b);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
Console.WriteLine("****Abstract Class Example****");
u.GetDetails("Suresh Dasari", "Hyderabad", 32);
Console.ReadLine();
}
}
}
if you observe above example, we defined an abstract class called “Info” with required
methods and the derived class “User” has implemented all the inherited abstract methods
and accessors.
C# Abstract Class Features:

 In c#, abstract classes cannot be instantiated.


 The abstract classes can contain both abstract and non-abstract methods and accessors.
 In c#, we should not use a sealed keyword with abstract class because the sealed keyword
will make a class as not inheritable but abstract modifier requires a class to be inherited. 
 A class that is derived from abstract class must include all the implementations of inherited
abstract methods and accessors.

Interface: In c#, interface is same like class but only difference is class can contain both
declarations and implementation of methods, properties and events but interface will contain
only the declarations of methods, properties and events that a class or struct can implement.

In c#, we can define an interface by using interface keyword

interface IUser
{
void InsertDetails();
}

C# Interface Example
using System;

namespace Tutlane
{
interface IUser
{
void GetDetails(string x);
}
class User : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Name: {0}", a);
}
}
class User1 : IUser
{
public void GetDetails(string a)
{
Console.WriteLine("Location: {0}", a);
}
}
class Program
{
static void Main(string[] args)
{
IUser u = new User();
u.GetDetails("Suresh Dasari");
IUser u1 = new User1();
u1.GetDetails("Hyderabad");
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe above example, we created an interface IUser and the two classes “User &
User1” implemented an interface IUser by providing an implementation for GetDetails() method
and we created an instance for interface “IUser” using User & User1 classes.

C# Multiple Inheritance with Interface


using System;

namespace Tutlane
{
interface IName
{
void GetName(string x);
}
interface ILocation
{
void GetLocation(string x);
}
interface IAge
{
void GetAge(int x);
}
class User : IName, ILocation, IAge
{
public void GetName(string a)
{
Console.WriteLine("Name: {0}", a);
}
public void GetLocation(string a)
{
Console.WriteLine("Location: {0}", a);
}
public void GetAge(int a)
{
Console.WriteLine("Age: {0}", a);
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
u.GetName("Suresh Dasari");
u.GetLocation("Hyderabad");
u.GetAge(32);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
C# Interface Overview
Following are the important properties of interface in c# programming language.

 In c#, interface is like an abstract class and it can contain only declarations of members such
as methods, properties, indexers and events.
 By default, the members of interface are public and we are not allowed to include any
other access modifiers.
 In c#, an interface cannot be instantiated directly, but it can be instantiated by
a class or struct that implements an interface.
 The class or struct that implements an interface must provide an implementation for all the
members that are specified in the interface definition. 
 The class or struct can implement multiple interfaces.

Boxing and unBoxing:

Boxing:

 The operation of Converting a Value Type to a Reference Type is called Boxing


 Boxing is used to store value types in the garbage-collected heap.
 Boxing is an implicit conversion of a value type to the type object or to any
interface type implemented by this value type.

int val=10;

Object obj=val; // Boxing

The first line we created a Value Type Val and assigned a value to Val.

The second line , we created an instance of Object Obj and assign the value of Val to
Obj.

From the above operation (Object Obj = i ) we saw converting a value of a Value Type
into a value of a corresponding Reference Type .

These types of operation is called Boxing.


Unboxing:

o Unboxing is simply the opposite of boxing.


o In it values are again shifted from the heap to the stack.
o In unboxing first of all it checks for the boxed object value and then it goes for
replica creation
oIt converts an object type back into the value type.

int val=10;

Object obj=val;//Boxing

int i=(int) obj;

example.:

using System;

using System.Windows.Forms;

namespace WindowsApplication1

{ public partial class Form1 : Form

public Form1()

InitializeComponent();

private void button1_Click(object sender, EventArgs e)

int Val = 10;

Object Obj = Val; //Boxing

int i = (int)Obj; //Unboxing

MessageBox.Show("The value is : " + i);


}

Collections
List:

In c#, List is a generic type of collection so it will allow to store only strongly typed objects i.e.
an elements of same data type and the size of list will vary dynamically based on our application
requirements like adding or removing an elements from the list.

In c#, list is a generic type of collection and it is provided by System.Collections.Generic


namespace.

As discussed, collection is a class so to define a list, we must need to declare an instance of the
list class before we perform any operations like add, delete, etc. like as shown below.

List<T> lst = new List<T>();

If you observe above list declaration, we created a generic list (lst) with an instance of list class
using type parameter (T) as placeholder with an angle (<>) brackets.

Here, the angle (<>) brackets will indicate that the list is a generic type and type parameter (T)
is used to represent a type of elements to be accepted by list.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
List<int> l = new List<int>();
l.Add(50);
l.Add(150);
l.Add(250); OUTPUT
l.Add(350);
l.Add(450);
l.Add(550);
foreach (object obj in l)
Console.WriteLine(obj);
Console.ReadLine();
}
}
}
Array –List:
In c#, Arraylist is used to store an elements of different data types and the size of arraylist can grow
or shrink dynamically based on the need of our application like adding or removing an elements
from arraylist.

In c#, arraylists are same as an arrays but only difference is arrays are used to store a fixed number of
same data type elements.

In c#, arraylist is a non-generic type of collection and it is provided


by System.Collections namespace.

As discussed, collection is a class so to define an arraylist, we must need to declare an instance of the
arraylist class before we perform any operations like add, delete, etc. like as shown below.

C# Arraylist Properties
Following are the some of commonly used properties of an arraylist in c# p rogramming language.

Description

Capacity It is used to pet or set the number of elements an arraylist can contain.

Count It is used to get the number of elements in arraylist.

IsFixedSize It is used to get a value to indicate that the arraylist has fixed size or not.

IsReadOnly It is used to get a value to indicate that the arraylist is readonly or not.

Item It is used g et or set an element at the specified index.

IsSynchronized It is used to get a value to inidicate that an access to arraylist is synchronized (thread safe)
or not.

C# Arraylist Methods
Following are the some of common Iy used methods of an arraylist to add, search, insert, delete or sort an
elements of arraylist in c# programming language.

Method Description

Add It is used to add an element at the end of arraylist.

AddRange It is used to add all the elements of specified collection at the end of arraylist.

Clear It will remove all the elements in array list.

Clone It will create a shallow copy of arraylist.

Contains It is used determine whether the specified element exists in arraylist or not.

CopyTa It is used to copy all the elements of an arraylist into another compatible array.
GetRang e It is used to return a specified range of arraylist elements starting from the specified index.
Example:
using System;
using System.Collections;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
ArrayList arrlist = new ArrayList();
arrlist.Add("Welcome");
arrlist.Add(100);
arrlist.Add(20.5);
arrlist.Add("Tutlane");
Console.WriteLine("ArrayList Count: " + arrlist.Count);
Console.WriteLine("ArrayList Capacity: " + arrlist.Capacity);
Console.WriteLine("*********ArrayList Elements********");
foreach (var item in arrlist)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
C# - Dictionary<TKey, TValue>
The Dictionary<TKey, TValue> is a generic collection that stores key-value pairs in no
particular order.

Dictionary Characteristics
 Dictionary<TKey, TValue> stores key-value pairs.
 Comes under System.Collection.Generic namespace.
 Implements IDictionary<TKey, TValue> interface.
 Keys must be unique and cannot be null.
 Values can be null or duplicate.
 Values can be accessed by passing associated key in the indexer e.g. myDictionary[key]
 Elements are stored as KeyValuePair<TKey, TValue> objects.

Example

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

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("Abhi", 250);
d.Add("Basavaraj", 500);
foreach (KeyValuePair<string, int> obj in d)
{
Console.WriteLine(obj);
} Console.ReadLine();
}
}
}

OUTPUT
Hashtable

The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash
code of the key. It uses the key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful key value.
Example:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("1", "Abhi");
ht.Add("2", "Basavaraj");

ICollection keys = ht.Keys;


foreach (String k in keys)
{
Console.WriteLine(ht[k]);
}
Console.ReadLine();
}
}
}

Output
Generic Classes

Generic means the general form, not specific. In C#, generic means not specific to a
particular data type.

C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static
methods, properties, events, delegates, and operators using the type parameter and
without the specific data type. A type parameter is a placeholder for a particular type
specified when creating an instance of the generic type.

A generic type is declared by specifying a type parameter in an angle brackets after a type
name, e.g. TypeName<T> where T is a type parameter.

Generic Class

Generic classes are defined using a type parameter in an angle brackets after the class
name. The following defines a generic class.

Example

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

namespace Non_generic_class
{
class genericdemo<a>
{
a student;
public genericdemo(a s) Output
{
student = s;
}
public a getstudent()
{
return student;
}
}

class Program
{
static void Main(string[] args)
{
genericdemo<int> gd = new genericdemo<int>(10);
genericdemo<char> d = new genericdemo<char>('A');
genericdemo<float> d1 = new genericdemo<float>(10.25f);
Console.WriteLine(gd.getstudent());
Console.WriteLine(d.getstudent());
Console.WriteLine(d1.getstudent());
Console.ReadLine();}}}
IComparable and Sorting
 It is an interface under a collection namespace
 The comparable interface can perform only to compare the values.
 In this comparable interface only compare source value to any destination value

 Sorting
 This method can be used to sort the particular values

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Icomparable
{
public class student : IComparable<student>
{
public int Sid;
public string Name;
public int Class;
public float Marks;
public int CompareTo(student other)
{
if (this.Sid > other.Sid)
return 1;
else if (this.Sid < other.Sid)
return -1;
else
return 0;
}
}
class Program
{
static void Main(string[] args)
{
student s1 = new student { Sid = 106, Name = "Amit", Class = 12, Marks = 400.12f };
student s2 = new student { Sid = 105, Name = "Suhan", Class = 11, Marks = 450.12f };
student s3 = new student { Sid = 102, Name = "Sohel", Class = 10, Marks = 550.12f };
student s4 = new student { Sid = 104, Name = "Pritam", Class = 12, Marks = 555.40f };
student s5 = new student { Sid = 101, Name = "Prakash", Class = 12, Marks = 480.12f };
student s6 = new student { Sid = 103, Name = "Keshav", Class = 11, Marks = 460.12f };
List<student> students = new List<student>() { s1, s2, s3, s4, s5, s6 };
students.Sort();

foreach (student s in students)


{
Console.WriteLine(s.Sid + " " + s.Name + " " + s.Class + " " + s.Marks);
}
Console.ReadLine();
}
}
}

Output

IEnumerable and IEnumerator

 IEnumerable and IEnumerator both are interfaces in C#.


 IEnumerable is an interface defining a single method GetEnumerator() that
returns an IEnumerator interface.
 IEnumerator has two methods MoveNext and Reset. It also has a property
called Current.

Example:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IEnumerablea
{
class Test : IEnumerable
{
Test[] Items = null;
int Index = 0;
public String Name { get; set; }
public string Surname { get; set; }
public Test()
{
Items = new Test[10];
}
public void Add(Test item)
{
Items[Index] = item;
Index++;
}
public IEnumerator GetEnumerator()
{
foreach (object o in Items)
{
if (o == null)
{
break;
} yield return o;
}
}
}
class Program
{
static void Main(string[] args)
{
Test t1 = new Test();
t1.Name = "Arjun";
t1.Surname = "Patil";
Test t2 = new Test();
t2.Name = "Dinesh";
t2.Surname = "Jadhav";
Test myList = new Test();
myList.Add(t1);
myList.Add(t2);
foreach (Test obj in myList)
{
Console.WriteLine("Name:- " + obj.Name + "Surname :- " + obj.Surname);
}
Console.ReadLine();
}
}
}

Output
C# .Net

UNIT – IV
Exception Handling
• An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e. at runtime, that disrupts the normal flow of the program’s instructions.
• Exception Handling in C# is a process to handle runtime errors. We perform exception
handling so that normal flow of the application can be maintained even after runtime errors.
• Exception is class.
• Exception handling is an in-build mechanism in .Net framework to detect and handle run
time errors.
• If the exception object is not caught and handled properly, the compiler will display an
error message and will terminate the program.
• If we want the program to continue with the exception of the remaining code then we
should try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as exception
handling.

Exception Handling Keywords


In C#, we use 4 keywords to perform exception handling:
• try- A try block identifies a block of code for which particular exceptions is activated. It
is followed by one or more catch blocks.
• catch - A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the catching
of an exception.
• finally - The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
• throw -A program throws an exception when a problem shows up. This is done using a
throw keyword.

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 1


C# .Net

Syntax
try
{
//statement which can cause an exception
}
catch(<exception class name> <variable>)
{
//statement for handling the exception
}
finally
{
//always excecute statement
}

Example
using System;
class exceptiondemo
{
static void Main()
{
try
{
Console.WriteLine("Enter the 1st Number");
int x=int.Parse(Console.ReadLine());
Console.WriteLine("Enter the 2st Number");
int y=int.Parse(Console.ReadLine());
int z=x/y;
Console.WriteLine("The Result is:"+z);
}

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 2


C# .Net
catch(DivideByZeroException ex1)
{
Console.WriteLine(ex1.Message);
}
catch(FormatException ex2)
{
Console.WriteLine(ex2.Message);
}
finally
{
Console.WriteLine("It always execute");
}
}
}

Raising Exception Using throw


• We have seen in the previous section how to handle exceptions which are automatically
raised by CLR.
• An exception can be raised manually by using the throw keyword.
• Any type of exceptions which is derived from Exception class can be raised using the throw
keyword.

Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionHandling

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 3


C# .Net
{
class throwdemo
{
static void Main()
{
Console.WriteLine("Enter the age ");
int age=int.Parse(Console.ReadLine());
try
{
if(age>=18)
{
Console.WriteLine("your are eligible for vote");
}
else
{
throw new Exception("Sorry You are not eligible for vote");
}
}
catch(Exception e) //catch block inherited from throw object
{
Console.WriteLine(e.Message);
}
}
}
}

Predefined Exception Classes

Exception Description
AggregateException Represents one or more errors that occur during

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 4


C# .Net
application execution.
ApplicationException It is base class for application-defined exceptions.
ArgumentException It is thrown when invalid argument provided to a method.
ArgumentNullException It is thrown when a method requires argument but no
argument is provided.
ArgumentOutOfRangeException It is thrown when value of an argument is outside the
allowable range.
ArithmeticException It is thrown when doing arithmetic, casting, or conversion
operation.
DivideByZeroException It is thrown when there is an attempt to divide an integral or
decimal value by zero.
DllNotFoundException It is thrown when a DLL specified in a DLL import cannot
be found.
ExecutionEngineException The exception that is thrown when there is an internal error
in the execution engine of the common language runtime.
FormatException The exception that is thrown when the format of an
argument is invalid, or when a composite format string is
not well formed.
IndexOutOfRangeException The exception that is thrown when an attempt is made to
access an element of an array or collection with an index
that is outside its bounds.
InsufficientMemoryException The exception that is thrown when a check for sufficient
available memory fails. This class cannot be inherited.
OutOfMemoryException The exception that is thrown when there is not enough
memory to continue the execution of a program.
OverflowException The exception that is thrown when an arithmetic, casting, or
conversion operation in a checked context results in an
overflow.
RankException The exception that is thrown when an array with the wrong
number of dimensions is passed to a method.
StackOverflowException The exception that is thrown when the execution stack
overflows because it contains too many nested method

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 5


C# .Net
calls.
SystemException Serves as the base class for system exceptions
namespace.
TimeoutException The exception that is thrown when the time allotted for a
process or operation has expired.
TypeLoadException The exception that is thrown when type-loading failures
occur.

Custom Exception Class


• Users can create their own exception called custom exception class by deriving Exception
or ApplicationException class, when rule is violated for that particular application.
• The .Net framework includes ApplicationException class. It was designed to use as a base
class for the custom exception class.
• They can greatly simplify and improve the error handling and thus increase the overall
code quality. Usually large-scale projects should define custom exceptions.

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 6


C# .Net

• Any Custom Exception you create needs to derive from the System.Exception class. You
can either derive directly from it or use an intermediate exception like SystemException or
ApplicationException as base class.
• ApplicationException is intended to be used by user code. An ApplicationException is
thrown by a user program, not by the common language runtime.

Using Statement Working with Components / Creating a .Net


framework Component

What is a component
• A component is reusable piece of code and is in the form of DLL (dynamic link library).
• Once a component is designed it can be reused from any kind of application like console or
windows application or web application.
• Once a component is designed in any programming language of .Net that can be reused
from any other programming language of .Net i.e Assembly will provide language
interoperability.
• To create component in .net we use class library templates.
• End user will never interact with DLL or component directly.
• Always end user will interact with some application and the application will interact with
component or DLL.

Steps to follow
1. Open visual studio
2. Go to file menu € new € Project € Select Class Library (Template)
3. Project name as MyClassLibrary
4. Click on ok

Example-
using System;
using System.Collection.Generic;
namespace MyClassLibrary

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 7


C# .Net
{
public class Arithmatic
{
int Num1, Num2, Result;
public int PNum1
{
set { Num1 = value; }
}
public int PNum2
{
set { Num2 = value; }
}
public int PResult
{
get { return Result; }
}
public void Add()
{
Result = Num1 + Num2;
}
public void Sub()
{
Result = Num1 - Num2;
}
public void Mul()
{
Result = Num1 * Num2;
}
public void Div()
{
Result = Num1 / Num2;
}
}
}

€in same project create onemore class and give class name as Math

using System;
using System.Collection.Generic;
namespace MyClassLibrary

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 8


C# .Net
{
public class Math
{
public int square(int x)
{
return x * x;
}
public int cube (int x)
{
return x * square(x);
}
}
}

Next close the visual studio and again open and create new project and give name as
consumeclasslibraryDLL.
Now right click on consumeclasslibraryDLL click on Add Reference then click on
Browse and select specified .dll file.

using System;
using System.Collection.Generic;
using MyClassLibrary;
namespace consuumeclasslibraryDLL
{
public class Program
{
static void Main(string[] args)
{
Arithmatic arth = new Arithmatic();
Math m = new Math();
Console.WriteLine("Enter Two Number:");
arth.PNum1 = Convert.ToInt32(Console.ReadLine());
arth.PNum2 = Convert.ToInt32(Console.ReadLine());
arth.Add();
Console.WriteLine("Sum is:" +arth.PResult);
arth.Sub();
Console.WritLine("Substraction is:"+arth.PResult);
arth.Mul();
Console.WritLine("Multiplication is:"+arth.PResult);

KLE SOCIETY’S COLLGE OF BCA GOKAK Page | 9


C# .Net
arth.Div();
Console.WritLine("Division is:"+arth.PResult);

Console.WriteLine("\n Enter Any Number :");


int N = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Square value is:"+m.square(N));
Console.WriteLine("Cube value is:"+m.cube(N));
Console.ReadLine();
}
}
}

Assembly
• An Assembly is a basic unit of application deployment and versioning.
• An Assembly is also called the building block of a .Net application.
• An Assembly is either a .exe or .dll(dynamic link library) file.
• An Assembly structure consists of the following parts:
➢ Assembly manifest: it consists of the information of an assembly.
➢ CIL code (logic part): Represents the .Net program as per Microsoft standards.
➢ Type information (Datatype): It consists of the information of all the types used in
the assembly.
➢ Resources: It consists of images that are part of the assembly, but not included in
the CIL/MSIL code.
• An assembly can be a single file or it may consist of the multiple files. In case of multi-
file, there is one master module containing the manifest while other assemblies exist as
non-manifest modules.
• .NET supports three kind of assemblies:
1. Private Assembly: Private assembly requires us to copy separately in all application
folders where we want to use that assembly’s functionalities; without copying we
cannot access the private assembly features and power. Private assembly means
every time we have one, we exclusively copy into the BIN folder of each
application folder.

KLE’S COLLEGE OF BCA GOKAK Page | 10


C# .Net
2. Public Assembly: Public assembly is not required to copy separately into all
application folders. Public assembly is also called Shared Assembly. Only one copy
is required in system level, there is no need to copy assembly into application
folder. Public assembly should install in GAC.

3. Satellite Assembly: Satellite assemblies are used for deploying language and
culture-specific resources for an application.

Shared assemblies
• Shared assemblies also called strong named assemblies are copied to a single location
usually the Global assembly cache.
• For all calling assemblies within the same application, the same copy of the shared
assembly is used from its original location. Hence, shared assemblies are not copied in the
private folders of each calling assembly.
• Each shared assembly has a four-part name including its face name, version, public key
token and culture information. The public key token and version information makes it
almost impossible for two different assemblies with the same name or for two similar
assemblies with different version to mix with each other.

DLL Hell
• Dll Hell refers to a set of problems caused when multiple applications attempt to share a
common component like a dynamic link library (DLL).
• If we install an application then dll of that application get stored in the registry, then if
we install other application that has same name .dll that means previously installed .dll
get overwrite by the same name new .dll. for newly installed application but previously

installed application can’t get execute further. This is big problem in context of version
of same application. This is Dll-Hell problem.
• This problem of dynamic link library (.dll) is resolved through Versioning.
• Versioning is the technique to provide version to the .dll to prevent them from replacement.

Page | 11
KLE’S COLLEGE OF BCA GOKAK
C# .Net

Side by Side Versioning


• Side-by-side execution is the ability to run multiple versions of an application or
component on the same computer.
• We can have multiple versions of the common language runtime, and multiple versions of
applications and components that use a version of the runtime, on the same computer at the
same time.
• Benefits of it are

➢ Strong-named assemblies.

➢ Version-aware code storage.

➢ Isolation.

Deploying .NET Assemblies in Global Assembly Cache.

• When the assembly is required for more than one project or application, we need to make
the assembly with a strong name and keep it in GAC or in Assembly folder by installing
the assembly with the GACUtil command.
• The GAC is a machine-wide independent location that allows Strong-Named assemblies
to register.
• It is a location where 2 versions of the same component can exist.
• In order to deploy an assembly in GAC, we have to create a strong name for anassembly.
• Strong name for an assembly guarantees the uniqueness by unqiue key pairs. Because an
assembly generated with a strong name consist of unique identity with its public key,
version number, text name, culture information and a digital signature.
• Steps to install or deploy an assembly in GAC using Microsoft .NET Framework SDK
v2.0/V.4.0
➢ Make sure that you installed .NET Framework SDK v2.0/V.40 in your machine.
➢ Click Start > All Programs > Administrative Tools > Microsoft .NET Framework
2.0/4.0 Configuration.
➢ Click Manage the Assembly Cache.
➢ Select Add an Assembly to the Assembly Cache.
➢ Browse and select your DLL, which you want to install it in GAC
➢ Click Open. This will deploy the selected assemblies into the Global Assembly
Cache (GAC).
➢ Restart the IIS.

Page | 12
KLE’S COLLEGE OF BCA GOKAK
C# .Net

Windows Forms Basics


• A Windows forms application is one that runs on the desktop computer. A Windows forms
application will normally have a collection of controls such as labels, textboxes, list boxes,
etc.
• Windows Forms is a Graphical User Interface (GUI) class library which is bundled in .Net
Framework.
• Its main purpose is to provide an easier interface to develop the applications for desktop,
tablet, PCs.

Page | 13
KLE’S COLLEGE OF BCA GOKAK
C# .Net
Control Description
Button Fires an event when a mouse click occurs or the Enter or Esc key is pressed.
Represents a button on a form. Its text property determines the caption
displayed on the button's surface.
CheckBox Permits a user to select one or more options.Consists of a check box with
text or an image beside it. The check box can also be represented as a button
by setting: checkBox1.Appearance = Appearance.Button.
CheckedListBox Displays list of items. ListBox with checkbox preceding each item in list.
ComboBox Provides TextBox and ListBox functionality. Hybrid control that
consists of a textbox and a drop-down list. It combines properties from both
the TextBox and the ListBox.
GridView Manipulates data in a grid format. The DataGridView is the foremost
DataGridView control to represent relational data. It supports binding to a database. The
DataGridView was introduced in .NET 2.0 and supersedes the DataGrid.
GroupBox Groups controls. Use primarily to group radio buttons; it places a
border around the controls it contains.
ImageList Manages a collection of images. Container control that holds a
collection of images used by other controls such as the ToolStrip, ListView,
and TreeView.
Label Adds descriptive information to a form. Text that describes the
contents of a control or instructions for using a control or form.
ListBox Displays a list of items—one or more of which may be selected. May
contain simple text or objects. Its methods, properties, and events allow
items to be selected, modified, added, and sorted.
ListView Displays items and subitems. May take a grid format where each row
represents a different item and sub-items. It also permits items to be
displayed as icons.
MenuStrip Adds a menu to a form. Provides a menu and submenu system for a form.
It supersedes the MainMenu control.
TablePanelLayout TablePanelLayout Groups controls. A visible or invisible container that
groups controls. Can be made scrollable. TablePanelLayout automatically
aligns controls vertically or horizontally
PictureBox Contains a graphic. Used to hold images in a variety of standard formats.
Properties enable images to be positioned and sized within control's
borders.
ProgressBar Depicts an application's progress. Displays the familiar progress bar
that gives a user feedback regarding the progress of some event such as file
copying.

Page | 14
KLE’S COLLEGE OF BCA GOKAK
C# .Net
RadioButton Permits user to make one choice among a group of options. Represents a
Windows radio button.

StatusStrip Provides a set of panels that indicate program status. Provides a status bar
that is used to provide contextual status information about current form
activities.
TextBox Accepts user input. Can be designed to accept single- or multi-line input.
Properties allow it to mask input for passwords, scroll, set letter casing
automatically, and limit contents to read-only.
TreeView Displays data as nodes in a tree. Features include the ability to collapse or
expand, add, remove, and copy nodes in a tree.

Menus
• An imperative part of the user interface in a Windows-based application is the menu.
• A menu on a form is created with a Menu object, which is a collection of MenuItem objects.
• You can add menus to Windows Forms at design time by adding the Menu control and
then adding menu items to it using the Menu Designer.
• Menus can also be added programmatically by creating one or more Menu controlsobjects
in to a form and adding MenuItem objects to the collection.
• Different types of menus available in C# are

➢ MenuStrip –used to create normal horizontal or vertical menus.

➢ ContextMenu- used to create popup menus. Menus appears when the mouse right
clicked and disappears once selection is made.
➢ ToolStrip- used to create menus when there is less space and these are called as
dropdown menus.
➢ StatusStrip- used to create status bar where status of form controls can be displayed.

Context Menu
• A context menu is a group of commands or menu items that can be accessed by right
clicking on the control surface. It usually contains some frequently used commands for

Page | 15
KLE’S COLLEGE OF BCA GOKAK
C# .Net
example Cut, Copy and Paste in a text editor.
• In Windows Forms, a context menu is created using the ContextMenuStrip control and its
command or menu items are ToolStripMenuItem objects.
• The Image property of ToolStripMenuItem is used to add an image to a menu item. In
design view, select the menu item and go to its property and click the ellipsis next to the
Image property and select image from the Local Resource or Project Resource File.
• A context menu is also known as a popup menu. A context menu appears when you right
click on a Form or on a control.

Type of items in ContextMenuStrip

1. MenuItem (ToolStripMenuItem): It is used to give a simple menu item like "Exit" in


the above example.
2. ComboBox(ToolStripComboBox): It is used to insert a ComboBox in the context
menu where the user can select or type an item in the ComboBox.
3. Separator (ToolStripSeparator): It is used to put a horizontal line (ruler) between
menu items.
4. TextBox (ToolStripTextBox): It is used to put a TextBox in the context menu where
the user can enter an item.

MenuStrip
• MenuStrip adds a menu bar to Windows Forms program.
• With this control, we add a menu area and then add the default menus or create custom
menus directly in Visual Studio.
• We can create a menu using MenuStrip control at design-time or using the MenuStrip class
in code at run-time or dynamically.
• Once a MenuStrip is on the Form, you can add menu items and set its properties and events.

Type of items in MenuStrip


• MenuItem (ToolStripMenuItem): It is used to give a simple menu item like "Exit" in
the above example.

Page | 16
KLE’S COLLEGE OF BCA GOKAK
C# .Net

• ComboBox(ToolStripComboBox): It is used to insert a ComboBox in the context menu


where the user can select or type an item in the ComboBox.
• Separator (ToolStripSeparator): It is used to put a horizontal line (ruler) between menu
items.
• TextBox (ToolStripTextBox): It is used to put a TextBox in the context menu where the
user can enter an item.

Toolstrip
• ToolStrip control provides functionality of Windows toolbar controls in Visual Studio
2010.
• This menu is also called as dropdown menu because in the form only an arrow will be
appearing when we click on arrow menu will appear.
• To create a ToolStrip control at design-time, simply drag and drop a ToolStrip control from
Toolbox onto a Form.
• At run time this can be created by creating the object of toolStrip class.

Type of items in toolstrip

• Button : Used to create a toolbar button that supports both text and images. Represents a
selectable ToolStripItem.
• Separator: Represents a line used to group items. Use this to group related items on a
menu or ToolStrip. The Separator is automatically spaced and oriented horizontally or
vertically to accord with its container.
• Label: Used to create a label that can render text and images that can implement
the ToolStripItem.
• DropDownButton: It looks like ToolStripButton, but it shows a drop-down area when
the user clicks it.
• SplitButton: Represents a combination of a standard button on the left and a drop-down
button on the right, or the other way around if the value of RightToLeft is Yes.
• TextBox: Control allows the user to enter text in an application. This control is used to

Page | 17
KLE’S COLLEGE OF BCA GOKAK
C# .Net
display a single line or multi lines of text or accept it as input.
• ComboBox: Displays an editing field combined with a ListBox, allowing the user to
select from the list or to enter new text. By default, a ToolStripComboBox displays an
edit field with a hidden drop-down list.

MDI
• MDI stands for Multiple Document Interface.
• It is an interface design for handling documents within a single application.
• When application consists of an MDI parent form containing all other window
consisted by app, then MDI interface can be used.
• Switch focus to specific document can be easily handled in MDI. For maximizing all
documents, parent window is maximized by MDI.

SDI
• SDI stands for Single Document Interface.
• It is an interface design for handling documents within a single application.
• SDI exists independently from others and thus is a stand-alone window.
• SDI supports one interface means you can handle only one application at a time.
• For grouping SDI uses special window managers.

Key Difference
SDI MDI
Stands for “Single Document Interface”. Stands for “Multiple Document Interface”
One document per window is enforced in SDI Child windows per document are allowed in
MDI.
SDI is not container control MDI is a container control
SDI contains one window only at a time MDI contain multiple document at a time appeared
as child window

SDI supports one interface. MDI supports many interfaces.

Page | 18
KLE’S COLLEGE OF BCA GOKAK
C# .Net
SDI uses Task Manager for switching between For switching between documents MDI uses
documents special interface inside the parent window
SDI grouping is possible through special MDI grouping is implemented naturally
window managers.
In SDI it is implemented through special code or For maximizing all documents, parent window is
window manager. maximized by MDI

It is difficult to implement in SDI. Switch focus to specific document can be easily


Handled

Dialog boxes
Dialog boxes are of two types, which are given below.

1. Modal dialog box

➢ A dialog box that temporarily halts the application and the user cannot continue
until the dialog has been closed is called modal dialog box.
➢ The application may require some additional information before it can continue or
may simply wish to confirm that the user wants to proceed.
➢ The application continues to execute only after the dialog box is closed, until then
the application halts.
➢ For example, when saving a file, the user gives a name of an existing file; a warning
is shown that a file with the same name exists, whether it should be overwritten or
be saved with different name. The file will not be saved unless the user selects
“OK” or “Cancel”.

2. Modeless dialog box

➢ It is used when the requested information is not essential to continue.

➢ The Window can be left open, while work continues somewhere else.
For example, when working in a text editor, the user wants to find and replace a particular word.
This can be done, using a dialog box, which asks for the word to be found and replaced. The user

Page | 19
KLE’S COLLEGE OF BCA GOKAK
C# .Net
can continue to work, even if this box.

Form Inheritance

• In order to understand the power of OOP, consider, for example, form inheritance, a new
feature of .NET that lets you create a base form that becomes the basis for creating more
advanced forms. The new "derived" forms automatically inherit all the functionality
contained in the base form. This design paradigm makes it easy to group common
functionality and, in the process, reduce maintenance costs.
• When the base form is modified, the "derived" classes automatically follow suit and adopt
the changes. The same concept applies to any type of object.

Example
Visual inheritance allows you to see the controls on the base form and to add new controls. In this
sample we will create a base dialog form and compile it into a class library. You will import this
class library into another project and create a new form that inherits from the base dialog form.
During this sample, you will see how to:
• Create a class library project containing a base dialog form.
• Add a Panel with properties that derived classes of the base form can modify.
• Add typical buttons that cannot be modified by inheritors of the base form.

KLE’S COLLEGE OF BCA GOKAK Page | 20


C# .Net

Developing Custom Controls

• Use Custom Panel/Panel as a border of a Frame for change the size of Form such as Width,
Height etc. and use Custom Buttons as a Control Box of a Frame.
• Use Custom Panel as a Top layered Title border of a frame and use label to display text of a
frame.
• To display icon on a frame we will set background image to added panel.
• Applying Mouse Events to panels and change properties of Form.

KLE’S COLLEGE OF BCA GOKAK Page | 21


C# .Net

Composite and Extended Controls

• Composite controls provide a means by which custom graphical interfaces can be created
and reused. A composite control is essentially a component with a visual representation.
• As such, it might consist of one or more Windows Forms controls, components, or blocks
of code that can extend functionality by validating user input, modifying display properties,
or performing other tasks required by the author.
• Composite controls can be placed on Windows Forms in the same manner as other controls.
• In the first part of this walkthrough, you create a simple composite control called ctlClock.
• In the second part of the walkthrough, you extend the functionality of ctlClock through
inheritance.

KLE’S COLLEGE OF BCA GOKAK Page | 22


Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769

UNIT V
A. Windows Service
A1. BASICS
1.1 Definition

Windows service is a computer program that runs in the background to execute some tasks.

1.2 Characteristics

• Windows Services are non UI software applications that run in the background.
• Windows services are usually starts when an operating system boots and scheduled to run in the
background to execute some tasks.
• Windows services can also be started automatically or manually.
• You can also manually pause, stop and restart Windows services.

1.3 Example
Some examples of Windows services are auto update of Windows, check emails, print documents, SQL Server
agent, file and folder scanning and indexing and so on.

If you open your Task Manager and click on Services tab, you will see hundreds of services running on your
machine. You can also see the statuses of these services. Some services are running, some have paused, and some
have stopped. You can start, stop, and pause a service from here by right click on the service.

1.4 Why a Windows Service?


One of the most common requirements of some businesses is long-running scheduled jobs based on some time
interval. For example: sending a newsletter everyday afternoon or send an email alert to the customer for every one
hour.

So building a Windows Service could be one of the reliable solutions to do the goal that can do the required job in
the behind the scenes without interfering others users on the same computer.

1.5 How to access Windows services?

You may also find all services running on your machine in the following ways:

• Go to Control Panel select “Services” inside “Administrative Tools”.


• Open Run window (Window + R) and type services.msc and press ENTER.

1.6 Purpose
You would typically want to use Windows services when you need to build and implement long-running jobs that
would be executed at predefined intervals of time. Your Windows service would continue to run in the background
while the applications in your system can execute at the same time. Note that a Windows service can continue to
execute in the background even if no one has logged into your system.

1.7 Advantages
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
• Enables you to create long-running executable applications that run in their own windows session.
• A service runs in the background, even if no-one is signed on to the machine.
• Anything you can imagine wanting to do without relying on a person to start an app and click a button is a
good candidate for a service.
• You don't need to have a session running. This is good for security, and also reduces overhead on the
server.
• You can handle server events such as shutdown.
• Any "server" you can think of - web server, ftp server, mail server - is a service, and so are many
background processes you may not often think of.
• Windows service can start running as soon as the machine is powered up, which makes ideal for running as
a server, http server.

1.8 How to view information about a Windows service?

In the Services window, for each of the services listed, you can see five things:

1. Name - The name of the service can be helpful if you want to get an idea of what that service does.
Unfortunately, though, this name is often too cryptic to help you understand what the service is all about.
2. Description - The description of the service shows some brief information about the service's purpose or
identity.
3. Status - Tells you whether that service is running or if it is stopped.
4. Startup Type - Shows you how that service is started by Windows. Services can be launched automatically,
automatically but with a delay, manually, or they can be disabled, which means that they are never started.
We will talk more about the startup type of Windows services and how to configure it, later in this tutorial.
5. Log On As - Lets you select whether the service is started using the Local System account or using another
user account that you manually specify.

1.9 How to start or stop a Windows service

Starting or stopping a service is easy: all you have to do is right-click the service (or tap and hold) and select the
desired action. To execute a service, press Start.

A2. Developing and Deploying


2.1 Step-by-step process of developing and installing a Windows Service to do a scheduled
job based on a time interval.
1. Open Visual Studio and from the menus select "File" -> "New" -> "Project...".A New Project window will open.
Choose "Visual C#" >> "Windows" project type and select "Windows Service" from the right hand side and name
the project "TestWindowsService"

2. After you click "OK", the project will be created and you will see the design view of the service as shown in the
screen. Right-click the "Service1.cs" file in Solution Explorer and rename it "to" Scheduler or any other name that
you want to give it. Then click “click here to switch to code view”.

Note:- In the code view, you can see two methods called OnStart() and OnStop(). The OnStart() triggers when the
Windows Service starts and the OnStop() triggers when the service stops.

3. Right-click the TestWindowService project, add a new class and name it "Library.cs". This class will be useful to
create the methods that we require in the project. And Create a log method (WriteErrorLog) to log the exceptions.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769

public static void Writelog(string message)


{
StreamWriter sw = null;
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\logfile.txt", true);
sw.WriteLine(System.DateTime.Now.ToString() + ":" + message);
sw.Flush();
sw.Close();

4. Now return to our Scheduler.cs file and declare a Timer. And Write the following code in the OnStart() method
and timer1_Tick():

protected override void OnStart(string[] args)


{

timer1 = new Timer();


this.timer1.Interval = 1000; //every 10 sec
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_tick);
timer1.Enabled = true;
library.Writelog("Service started");

private void timer1_tick(object sender,ElapsedEventArgs e)


{
library.Writelog("Service Started ,and Task done successfully");
}

5.Write the following code in the OnStop() method:

protected override void OnStop()


{
timer1.Enabled = false;
library.Writelog("Service Stoped");
}

6.Now return to the Scheduler.cs [Design] and right-click on the editor window then click "Add Installer".Then you
can see that there will be a new file called "ProjectInstaller.cs" as shown in the following.

7. Right-click on the "serviceInstaller1" and click "Properties".Change the ServiceName to "Test Windows Service"
(or your own name) and StartType to "Manual" (or you can choose "Automatic" if you need this service to be
automatic).

8. Right-click the serviceProcessInstaller1, go to the properties window and change "Account" to "LocalSystem".

9. Build the project to see the .exe file at the location where you created the solution. That's all. Your Windows
Service is all ready to install in your machine.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
2.2 Installing the Windows Service
Step 1:
Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" then click
"Developer Command Prompt for VISUAL STUDIO".
Step 2:
Type the following command:

cd <physical location of your TestWindowService.exe file>


Next type the following command:

Step 3:
InstallUtil.exe “TestWindowService.exe”

Step 4:
and press Enter.

Here you go, the TestWindowService is installed successfully.

A3. Debugging Windows Services in C#


3.1 What is mean by Debugging?
In software development, debugging involves locating and correcting code errors in a computer
program. Debugging is part of the software testing process and is an integral part of the entire software development
lifecycle.

The compiled executable file that a service application project creates must be installed on the server before the
project can function in a meaningful way. You cannot debug or run a service application by pressing F5 or F11.
Here we are going to see how to debug our own windows services.

3.2 Steps for debugging windows services

Step 1: Install your service. In my case it is the service which I created and installed as mentioned in my
previous article i.e. Birthday Wish Scheduler in C#.

Step 2: Start the service.

Step 3: Open your project in Visual Studio.NET.

Step 4: Then choose processes from the Debug menu. The following windows will appear.

Step 5: Click on "Show system processes".

Step 6: From the available processes, look for the process created by your service. The process name will be
same as the executable file of the service.

Step 7: Clicking Attach will show "Attach to Process" dialog box.

Step 8: Choosing the appropriate option will bring the application in debug mode.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
Step 9: Insert breakpoints to debug the service.

Step 10: From the service control manager, use different options like start, stop etc. to debug it.

A4.Sending Custom events

4.1 What is mean by Custom event?


Custom events let you define the success type that you want to track. Although similar to
predefined events, custom events let you define your own success metric. For example, if you have a newsletter,
your success event could be Registration .

4.2 Creating and Calling custom events.


We can create or send custom events using OnCustomCommand

OnCustomCommand executes when the Service Control Manager (SCM) passes a custom command to the service.
Specifies actions to take when a command with the specified parameter value occurs.

The only values for a custom command that you can define in your application or use in OnCustomCommand are
those between 128 and 256.
Integers below 128 correspond to system-reserved values.

4.2.1 Create One Windows Service & Implement Below Code in Service:

namespace MyWindowsService
{
public partial class Service1 : ServiceBase
{
public enum SimpleServiceCustomCommands { Command1 = 128, Command2 =129, Command3 = 130};

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)


{
}

protected override void OnStop()


{
}

protected override void OnCustomCommand(int command)


{
base.OnCustomCommand(command);
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
switch(command)
{
case(int)SimpleServiceCustomCommands.Command1:
//Command1 Implementation
break;

case(int)SimpleServiceCustomCommands.Command2:
//Command2 Implementation
break;

case(int)SimpleServiceCustomCommands.Command3:
//Command3 Implementation
break;
default:
break;

}
}
}}

4.2.2 Call Windows Service CustomCommands From User Application:

• Create Service Controller Object

ServiceController Controller = new ServiceController("MyWindowsService");

• Start the Windows Service

Controller.Refresh(); //Gets the current status of service


if (Controller.Status == ServiceControllerStatus.Stopped)
{
Controller.Start();
}

• Call CustomCommands Using Controller Object

if (Controller.Status == ServiceControllerStatus.Running)
{
Controller.ExecuteCommand(128);
}
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769

B. PACKAGING AND DEPLOYMENT


B1.BASICS

When you want to deploy a web application project to a remote server environment, your first task is to build the
project and generate a web deployment package.

1.1 What Is a Web Deployment Package?

When you build and deploy a web application project, either by using Visual Studio 2010 or by using MSBuild
directly, the end result is typically a web deployment package. The web deployment package is a .zip file. It contains
everything that IIS and Web Deploy need in order to recreate your web application, including:

• The compiled output of your web application, including content, resource files, configuration files, JavaScript
and cascading style sheets (CSS) resources, and so on.
• Assemblies for your web application project and for any referenced projects within your solution.
• SQL scripts to generate any databases that you're deploying with your web application.

Once the web deployment package has been generated, you can publish it to an IIS web server in various ways.

1.2 What is meant by Web Deploy?


Web Deploy is an extensible client-server tool for syncing content and configuration to IIS. Web Deploy is used
primarily in two scenarios: Developers use it to sync (aka 'publish') a compiled web applications (ASP .Net, PHP
etc) from developer tools (Visual Studio, WebMatrix, etc) to IIS

1.3 What is meant by deployment of web APP?


Deployment is the term used for the process of installing a web application (either a 3rd party WAR or your own
custom web application) into the Tomcat server. Web application deployment may be accomplished in a number
of ways within the Tomcat server.

1.4 There are two categories of ASP.NET deployment:


• Local deployment : In this case, the entire application is contained within a virtual directory and all the
contents and assemblies are contained within it and available to the application.
• Global deployment : In this case, assemblies are available to every application running on the server.

B2.TYPES OF DEPLOYMENT
There are different techniques used for deployment, however, we will discuss the following most common and
easiest ways of deployment:

• XCOPY deployment
• Copying a Website
• Creating a set up project
• Creating a Web Setup Project
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
2.1 XCOPY Deployment

XCOPY deployment means making recursive copies of all the files to the target folder on the target machine. You
can use any of the commonly used techniques:

• FTP transfer
• Using Server management tools that provide replication on a remote site
• MSI installer application
XCOPY deployment simply copies the application file to the production server and sets a virtual directory there.
You need to set a virtual directory using the Internet Information Manager Microsoft Management Console (MMC
snap-in).

2.2 Copying a Website

The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy Web Site menu
option. This menu item allows copying the current web site to another local or remote location. It is a sort of
integrated FTP tool.
Using this option, you connect to the target destination, select the desired copy mode:

• Overwrite
• Source to Target Files
• Sync UP Source And Target Projects
Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is
done from Visual Studio environment. However, there are following problems with both the above deployment
methods:

• You pass on your source code.


• There is no pre-compilation and related error checking for the files.
• The initial page load will be slow.

2.3 Creating a Setup Project

In this method, you use Windows Installer and package your web applications so it is ready to deploy on the
production server. Visual Studio allows you to build deployment packages. Let us test this on one of our existing
project, say the data binding project.
Open the project and take the following steps:
Step (1): Select File -> Add -> New Project with the website root directory highlighted in the Solution Explorer.

Step (2): Select Setup and Deployment, under Other Project Types. Select Setup Wizard.

Step (3): Choosing the default location ensures that the set up project will be located in its own folder under the
root directory of the site. Click on okay to get the first splash screen of the wizard.

Step (4): Choose a project type. Select 'Create a setup for a web application'.

Step (5): Next, the third screen asks to choose project outputs from all the projects in the solution. Check the check
box next to 'Content Files from...'
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
Step (6): The fourth screen allows including other files like ReadMe. However, in our case there is no such file.
Click on finish.

Step (7): The final screen displays a summary of settings for the set up project.

Step (8): The Set up project is added to the Solution Explorer and the main design window shows a file system
editor.

Step (9): Next step is to build the setup project. Right click on the project name in the Solution Explorer and select
Build.

Step (10): When build is completed, you get the following message in the Output window:

Two files are created by the build process:

• Setup.exe
• Setup-databinding.msi
You need to copy these files to the server. Double-click the setup file to install the content of the .msi file on the
local machine.

2.4 Creating a Web Setup Project

You can create an installation package to facilitate setting up your Web service in a production environment. This
produces an .MSI file.

To create an installation package to produce an .MSI file using Visual Studio

Step 1: Open your published ASP.NET Web service project.

Step 2: In Solution Explorer, right-click the solution node, click Add, and then click New Project.

Step 3: In the Add New Project dialog box, in the Project Types area, expand Other Project Types,
expand Setup and Deployment Projects, and then select Visual Studio Installer. In the Templates area,
select Web Setup Project.

Step 4: In the Name text box, type a name for the Web Setup Project. You can use the same name as the ASP.NET
Web Service project and add "_Setup" as a suffix and then click OK.

Step 5: In Solution Explorer, right-click the newly created Web setup project node, and point to View, and then
click File System.

Step 6: In the File System window, right-click the Web Application Folder node and point to Add, then
click Project Output.

Step 7: In the Add Project Output Group dialog box, select Primary Output and Content Files from the
ASP.NET Web Service project and then click OK.

Step 8: In Solution Explorer, expand the Detected Dependencies node under the Web setup project.

Step 9: Select all dependencies. In the Properties window, set the Exclude property to True.

Step 10: Build your Web setup project.


Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769

B3.Working with a Merge Module Project


3.1 Merge Module
Merge modules are used to deliver shared code, files, resources, registry entries, and setup logic to applications as a
single compound file.

3.2 Merge Module Project


Merge module projects are used for the packaging of files or components that are shared between multiple
applications.

3.2 Example
Here we will take example as Crystal report for merge module
How do you include Crystal Reports Merge module in deployment

Step 1: Copy CrystalReportsRedist2005_x86.msm to the \Program Files\Common Files\Merge Modules folder.

Step 2: Start Visual Studio.

Step 3: In the File menu, select New|Project.


Step 4: In the “New Project” dialog box, select a Windows Setup Project or a Web Setup Project.

Step 5: In the “Solution Explorer”, select your setup project, right-click, and select Add|Merge Module from the
pop-up menus:

Step 6: Add CrystalReportsRedist2005_x86.msm to your project:

Note that Microsoft_VC80_ATL_x86.msm and policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically


included when you add CrystalReportsRedist2005_x86.msm to your project:

Step 7: Build your project.

Step 8: Run your deployment setup.

When you installed generated setup it will share crystal report msi automatically for your application.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
B4. Debugging and Tracing.

4.1. Debugging

4.1.1 What is Debugging in ASP.NET?


Debugging is the process of adding breakpoints to an application. These breakpoints are used to pause the execution
of a running program. This allows the developer to understand what is happening in a program at a particular point
in time.

4.1.2 Example

Let's take an example of a program. The program displays a string "We are debugging" to the user. Suppose when
we run the application, for some reason, the string is not displayed. To identify the problem we need to add a
breakpoint. We can add a breakpoint to the code line which displays the string. This breakpoint will pause the
execution of the program. At this point, the programmer can see what is possibly going wrong. The programmer
rectifies the program accordingly.

Here in the example, we will use our 'DemoApplication' that was created in earlier. In the following example, we
will see

• How to make the demo application display a string.


• How to add breakpoints to an application.
• How to debug the application using this breakpoint.

Step 1) Let's first ensure we have our web application open in Visual Studio. Ensure the DemoApplication is open
in Visual Studio.

Step 2) Now open the Demo.aspx.cs file and add the below code line.

• We are just adding the code line Response.Write to display a string.


• So when the application executes, it should display the string "We are debugging" in the web browser.

Step 3) Now let's add a breakpoint. A breakpoint is a point in Visual Studio where you want the execution of the
program to stop.

1. To add a breakpoint, you need to click the column where you want the breakpoint to be inserted. So in our
case, we want our program to stop at the code line "Response.Write". You don't need to add any command
to add a breakpoint. You just need to click on the line on which you want to add a breakpoint.
2. Once this is done, you will notice that the code gets marked in red. Also, a red bubble comes up in the
column next to the code line.

Note: - You can add multiple breakpoints in an application

Step 4) Now you need to run your application using Debugging Mode. In Visual Studio, choose the menu option
Debug->Start Debugging.

When you perform all the steps correctly, the execution of the program will break. Visual Studio will go to the
breakpoint and mark the line of code in yellow.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
Now, if the programmer feels that the code is incorrect, the execution can be stopped. The code can then be
modified accordingly. To continue proceeding the program, the programmer needs to click the F5 button on the
keyboard.

4.2 Tracing

4.2.1 What is Tracing in ASP.NET?

Application tracing allows one to see if any pages requested results in an error. When tracing is enabled, an extra
page called trace.axd is added to the application. (See image below). This page is attached to the application. This
page will show all the requests and their status.

Let's look at how to enable tracing for an application.

Step 1) Let's work on our 'DemoApplication'. Open the web.config file from the Solution Explorer.

Step 2) Add the below line of code to the Web.config file.

<trace enable="true" pageOutput="false" requestLimit="40" localOnly="false"/>

The trace statement is used to enable tracing for the application.

• The 'requestLimit' in trace statement is used. It specifies the number of page requests that has to be traced.
• In our example, we are giving a limit of 40. We give limit because a higher value will degrade the
performance of the application.

Run the "demoapplication" in Visual Studio.

Output:-

If you now browse to the URL – http://localhost:53003/trace.axd , you will see the information for each request.
Here you can see if any errors occur in an application. The following types of information are shown on the above
page

1. The time of the request for the web page.


2. The Name of the web page being requested.
3. The status code of the web request. (status code of 200 means that the request is successful).
4. The View details which you allow to view more details about the web request. An example of this is shown
below. One important detailed information provided is the header information. This information shows
what is the information sent in the header of each web request.
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769

4.2.2 Page Level Tracing

Page tracing shows all the general information about a web page when it is being processed. This is useful in
debugging if a page does not work for any reason.

Visual Studio will provide detailed information about various aspects of the page. Information such as the time for
each method that is called in the web request. For example, if your web application is having a performance issue,
this information can help in debugging the problem. This information is displayed when the application run's in
Visual Studio.

Let's look at how to enable tracing for an application at a page level.

Step 1) Let's work on our DemoApplication. Open the demo.aspx file from the Solution Explorer

Step 2) Add the below line of code to enable page tracing. In the Page declaration, just append the line
Trace="true". This code line will allow page level tracing.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs"


Inherits="DemoApplication.Demo" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.ore/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server”>
</form>
</body>
</html>

Run the application in Visual Studio.

Output:-

Now when the web page Demo.aspx is displayed, you will get a whole lot of information about the page.
Information such as the time for each aspect of the page lifecycle is displayed on this page.

You might also like