Unit 1 C#
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
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.
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.
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 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
1. Net Architecture
2.6 Metadata
Net Framework
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.
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).
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
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.
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).
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).
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#.
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
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).
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
1 Visual Basic comes from Microsoft Java comes from sun Microsystem
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
Note-
In JAVA ---------------- > import package (same behaves like C and C++ header file)
In C# ------------------- > using System (same behaves like C and C++ header file)
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 ()
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).
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”);
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”);
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()
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++.
Console.ReadLine();
In which every predefined data type are already define like classes and structure.
Ex.
Class student
-------- members
Ex.
Comments
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
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.
[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.
The following diagram will illustrate more detail about different data types in c# programming language.
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
The following table lists the reference data types in c# programming language with memory size and range of values.
object Object - -
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.
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] - 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.
Now we will see how to define variables in our c# applications with examples.
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.
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;
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
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.
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
This is how we can use arithmetic operators in c# programming language to perform the basic arithmetic calculations on
operands 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.
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.
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.
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.
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;
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.
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.
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.
+= 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
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;
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)
Unary +, -, !, ~
Multiplicative *, /, %
Additive +, -
Equality ==, !=
Category Operator(s)
Bitwise &, |, ^
Logical &&, ||
Conditional ?:
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
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.
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:
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;
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)
{
}
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.
Following is the detailed description of various data members that we used in the above c# class example.
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.
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.
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.
protected It is used to specifies that access is limited to the containing type or types derived from the
containing class.
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);
}
}
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
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();
}
}
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.
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.
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.
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.
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.
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;
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.
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.
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.
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.
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.
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.
using System;
namespace Tutlane
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.
using System;
namespace Tutlane
{
class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
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.
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.
Generally, in c# the static constructor will not accept any access modifiers and parameters. In simple words, we can say it’s
parameter less.
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();
}
}
}
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.
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;
}
}
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.
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.
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.
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.
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
{
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);
C# Delegate Types
In c#, we have a two different type of delegates available, those are
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
{
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()
{
Inheritance:
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.
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.
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()
{
}
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:
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.
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.
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:
int val=10;
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 .
int val=10;
Object obj=val;//Boxing
example.:
using System;
using System.Windows.Forms;
namespace WindowsApplication1
public Form1()
InitializeComponent();
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.
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.
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.
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.
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.
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
AddRange It is used to add all the elements of specified collection at the end 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");
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();
Output
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.
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);
}
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExceptionHandling
Exception Description
AggregateException Represents one or more errors that occur during
• 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.
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
€in same project create onemore class and give class name as Math
using System;
using System.Collection.Generic;
namespace MyClassLibrary
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);
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.
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
➢ Strong-named assemblies.
➢ Isolation.
• 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
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
➢ 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.
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.
Page | 16
KLE’S COLLEGE OF BCA GOKAK
C# .Net
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.
• 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
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
Dialog boxes
Dialog boxes are of two types, which are given below.
➢ 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”.
➢ 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.
• 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.
• 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.
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.
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.
You may also find all services running on your machine in the following ways:
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.
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.
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.
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
4. Now return to our Scheduler.cs file and declare a Timer. And Write the following code in the OnStart() method
and timer1_Tick():
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:
Step 3:
InstallUtil.exe “TestWindowService.exe”
Step 4:
and press Enter.
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.
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 4: Then choose processes from the Debug menu. The following windows will appear.
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 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.
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();
}
case(int)SimpleServiceCustomCommands.Command2:
//Command2 Implementation
break;
case(int)SimpleServiceCustomCommands.Command3:
//Command3 Implementation
break;
default:
break;
}
}
}}
if (Controller.Status == ServiceControllerStatus.Running)
{
Controller.ExecuteCommand(128);
}
Ligand Software Solutions Contact: 8722585715
Mail: [email protected] 8147322769
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.
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.
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).
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:
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:
• 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.
You can create an installation package to facilitate setting up your Web service in a production environment. This
produces an .MSI file.
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.
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 5: In the “Solution Explorer”, select your setup project, right-click, and select Add|Merge Module from the
pop-up menus:
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.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
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.
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.
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
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.
Step 1) Let's work on our 'DemoApplication'. Open the web.config file from the Solution Explorer.
• 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.
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
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.
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.
<!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>
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.