Professional Documents
Culture Documents
C Net
C Net
MS.NET
MS.NET
MS.NET
MS.NET
MS.NET
1.0
1.1
2.0
3.5
4.0
----2000
----2003
----2005
----2008
----2010
LINQ
MICROSOFT.NET
C # .NET
VB .NET
J# . NET
JSCRIPT.NET
PYTHONSCRIPT.NET
PEARLSCRIPT.NET
EFFEL.NET
F#.NET
COBOLSCRIPT.NET
VISUAL C++.NET
VBSCRIPT.NET ETC.. ETC..
d).ISS: Internet security server it is used for applying security for ASP.net applications
e).BISTALK SERVER: it is used to store the information in XML format
f).EXCHANGE SERVER: it is used for exchanging mails
g).ECOMMERCE: it is used for online banking etc.
5).NET TOOLS: it is used for compiling and executing or checking the structure of files by using builtin tools like Compilers,interpreters,debuggers,assemblers,disassemblers etc
APPLICATION LAYER: This layer is used for presenting the application by developing the front ends.
This layer provides some collection of languages and application from which we can choose and develop
the application
BASECLASSLIBRARIES: This layer provides some predefined functionalities which are used by
application layer for developing the application
TRANSLATING LAYER: This layer is used to convert your application to OS understandable language
by managing the memory, checking the security and monitoring the program
LIFE CYCLE EXECUTION OF .NET APPLICATION
->Any .NET application choose their respective
compilers and compiles the program .
-> Any .NET application compiled format is IL
code which is given to CLR for converting it to
native OS understandable format at the time of
execution
IL (intermediate language):it is the compiled format of any .NET program which is OS independent.
It can be called as MSIL, CIL, and assembly
IL format is of two types
METADATA: it is used to describe the data of the IL file i.e. it provides the structure of the program like
class names, method names etc
CODE: it provides the actual instructions of IL file
RESOURCE: it provides the additional information like images,cursors,icons etc
MANIFEST: it provides documentary information like product name, company name, version no, strong
name etc.
PE WRAPPER: it contains some executable format which invokes the CLR.
Note: if you want to view the complete IL file then ILDASM.exe
ILDASM.exe:it is a build-in tool of .net used to show the wrapper file or IL file
Managed Code
Unmanaged Code
Any code that tries to bypass the CLR and attempts to handle these functions itself is considered "unsafe";
and the compiler would not compile the code. If the user insists on bypassing the CLR memory
management functionality then he must specifically write such code in using the "unsafe" and "fixed" key
words. Such a code is called "unmanaged" code.
Namespaces
Namespaces are a mechanism for logically grouping similar classes into a hierarchical structure. This
prevents naming conflicts. The structure is implemented using dot-separated words. The top level
namespace for most of the .NET framework is System . Under the System namespace you'll find the
following:
System.IO
System.Net
System.Net.Sockets
System.Reflection
System.Threading
ADO.NET
(Data and XML)
CLR
The .NET Framework has a huge set of classes. They are grouped under namespaces for easy
accessibility and better categorization.
The methods has to be called along with its complete path in the hierarchy, a really tiresome
process to do repeatedly. This is when the using keyword comes into aid by importing the
namespaces. When imported, the classes inside the namespace can be accessed just by their
names.
Any .NET application that we make, has to reside in a namespace of its own, so we write the
statement namespace Hello World. All the classes you create under this namespace can be
accessed as NameSpaceName.ClassName.
Main is the entry point for the application. The entry point must be declared as static because that
way the main function can be invoked even without creating an object of the Program class. Also
the name of the entry function should be Main, the capital M counts too.
String[ ] args
Any application can take parameters, when run from the command prompt. Say you ran the
Notepad application as follows Notepad.exe MyFile.txt. The text MyFile.txt is the parameter
passed to it, Notepad reads this parameter and opens the file. Similarly, we may need to work
with arguments passed to your application. This is why we use the string[ ] args inside the Main
function.
Console.WriteLine(zenic)
The Console class resides in the System namespace and represents the standard input, output and
error streams for console application.
Console.ReadLine();
This nifty method will allow you to take in user input. Whether the user input is numeric or
alphabetic, it will take the input as a string or text .
Tokens
The basic element recognized by the compiler is the "token." A token is source
source-program text that
the compiler does not break down into com
component elements.
token:
keyword
identifier
constant
operator
Escape Sequences
Variables
A Variable is a named location that stores a value. Although variables are physically stored in the
RAM, their actual memory address is not known to the programmer. We can use the variables via
the name we give them. These are the rules for naming a variable:variable:
The name must begin with a letter or an underscore & can be followed bbyy a sequence of letters
(A-Z), digits (0-9)
9) or underscore (_)
A variable name must not be the same as a reserved keyword such as using, public, etc.
Variables with the same scope cannot have the same name
Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be
different.
All variables can be divided into seven main categories depending on the context of usage:
Static variables
Variable of instance
Array's elements
Returned values
Local variables.
Variable Declaration
For Example:
int Age;
char Sex;
string Name;
bool IsMarried;
Initialization
Displaying Variables
Comments
// This is a comment
/* These are two lines
of comments */
Constants
Constants are variables whose values once defined cannot be changed by the program.
Data Types
A data type is a classification done by identifying one of various types of data, as floating-point,
integer, or boolean, stating the possible values, operations that can be done and the way the
values of that type are stored.
.NET framework has provided its build in data types under CTS concept
CTS provides common data types for all .NET languages and they are build in structures
Value Types
Value type objects directly contain the actual data in a variables. With value types, the variables
each have their own copy of the data, and it is not possible for operations on one to affect the
other. Memory allocation on Stack.
int i = 10;
Reference Types
Reference type variables stores the reference of the actual data. With reference types, it is
possible for two variables to reference the same object, and thus possible for operations on one
variable to affect the object referenced by the other variable. Memory allocation on Heap.
Type conversion: it is a process of converting one data type to another data type
BOXING : it is a process of converting value type data type to reference type data type
Boxing requires explicit conversion by using To String(); which converts any data type to string type
Example:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 10;//value type
Type casting: converting one value type to another value type or one reference type to another reference
type is called as type cast
Widening: it is a process of converting small data type values to large data type values. it does not
require explicit casting
Exmple:
class Program
{
static void Main(string[] args)
{
int i = 1000;//value type
long l;//value type
l = i;//widening
Console.WriteLine("i={0} and l={1}",i,l);
Console.ReadLine();
}
}
Narrowing : it is a process of converting large data type values to small data types this type of
conversion is risky becoz you may lose the value in it requires explicit conversion
Checked block checks the narrowing conversion is valid or not by checking the range of the data
types and raises runtime error if invalid
Syntax: checked
{
Stat1..;
Stat2..;
Stat3..;
}
Unchecked block use to allow the narrowing conversion by truncating the value
Ex: if byte is assigned with 256 then automatically the value truncates to 0 becoz the range of
byte is 0-255
Syntax: unchecked
{
Stat1;
Stat2;
}
Example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("range of byte is {0}{1}", byte.MinValue, byte.MaxValue);
checked
{
Example 1:
private void button1_Click(object sender, EventArgs e)
{
int sal = 5000;
MessageBox.Show(sal); // It will give Error.
MessageBox.Show(sal . ToString());
}
Obs: 1) MessageBox.Show() is capable to print only strings.
2) Local variables must be initialized before using.
Example 2:
private void button1_Click(object sender, EventArgs e)
{
byte b1 = 10, b2 = 20;
byte c = b1 + b2;
int c = b1 + b2;
// Error
// Correct
MessageBox.Show(c.ToString());
}
Obs: Above statement gives an error as [+] operator returns int as output, which cannot be stored in
byte.
Example 3:
private void button1_Click(object sender, EventArgs e)
{
float x = 4.3;
// Error
float x = 4.3f;
// Correct
//Wrong
int i = int.Parse(textBox2.Text);
int ts = s + i;
MessageBox.Show(ts.ToString());
}
Obs:-
Adding numbers.
Concatenating Strings.
10 + 10 = 1010
10 + 10 = 20
10 + 10
= Error
ToInt16(--)
Convert..ToByte(--)
ToInt32(--)
Convert..ToFloat (--)
ToInt64 (--)
Convert..ToDouble (--)
Convert..ToDecimal (--)
Convert..ToBoolean (--)
Note: If we give file name like (Convert). We give this file name it will not show any methods when
typing convert.(Dot), because the file name is a predefined method. So we give a file name other like
(Convert Demo).
Example :7
private void button1_Click(object sender, EventArgs e)
{
int i = 65;
char c = Convert.ToChar(i);
MessageBox.Show(c.ToString());
}
Example :8 if-else
private void button1_Click
{
int i = 10, j = 5;
if (i > j)
this.BackColor = Color.Green;
else
this.BackColor = Color.Red;
}
Example :9 switch case
private void button1_Click_1(object sender, EventArgs e)
{
int i = int.Parse(textBox1.Text);
switch (i)
{
case 1:
this.BackColor = Color.Green;
break;
case 2:
ColorDialog cd = new ColorDialog();
cd.ShowDialog();
this.BackColor = cd.Color;
break;
default:
Application.Exit();
break;
}
}
OOPS CONCEPTS
OOPS is a concept which relates to a real world problem in a system design by providing everything as a
object.
Code founder of oops- Grady booch
OOPS will provide communication between different objects and helps the information
displaying fastly
Class:
Features of OOPS:
Data organization: it is used for organizing the data in a single block for fast accessing and to
increase the performance of the application because in c program data was scattering in a stack
which requires searching time while accessing the data
Data security: with the traditional languages it supports global variables declarations where data
is not secured so OOPS provides accessibility levels for the data by using access modifiers i.e.
private and protected
Reusability :it enables the developer to use the existing functionality for developing a new
software model fastly with less cost and maintenance
Extensibility :it provides to manipulate the existing software model by adding the new features
required with the feature criteria
Reimplementation :it supports the changing of body of the existing functionality depending on a
criteria
Inheritance
3.
Polymorphism
Encapsulation: it is process of wrapping up of data members, methods in a single entity for providing
data organization and security.
Inheritance :it is a process of defining a new software model from the existing one by using reusability
and extensibility
Polymorphism: it is a process of defining multiple forms with same name to provide reimplementation
and versioning of software's
OOPS is supported by different languages and provides a new classification
Object: An object is any thing that exists physically.ait is a variable of a class type which holds the
address of the class by allocating the memory for it and can provide accessibility for the class members
It is also called as instance of the class or blue print of a class
Object memory are allocated on heap
Types of objects:
1. Reference object: an object which informs the compiler that it is of a particular class type whose
memory will be allocated on stack
Syn: <class name> <object>;
Ex: Sample s;
Generally reference object is supported with late or dynamic binding of polymorphism
2. Instance object: an object which informs the compiler that it is of a particular class type and holds
the address of a specific class
Its syntax performs two operations
Allocate the memory for the class on heap
Assign the address of the class in the object on the stack
Types of Classes:
Data members
These are the variables which are used to store some data
Every variable will have some data type and that data type specifies that the type of data we are storing in
a variable.
Let us consider a class called customer the members of the customer class may
may be
Ex: int CustId;
string CustName ;
string CustAddress
Int Age; etc
METHODS IN CLASSES
A method is a sub program which contains some executable statements and are executed when u call a
method.
Note: Procedure will does not return any value
Method will always return a value
C#.net supports only methods but vb.net supports procedures.
Keywords
Return types:
Mode: value,ref,out,params
Return Type
The return type determines the type of value that the function will return. It can be any of the atomic data
types (int, char, string, bool, float, etc) or the user defined types (enums, objects, structures). A function
that does not return any value should have a return type of void.
Function Name
The function name can be anything that follows the naming rules.
Parameters
Functions take values as input, process it and return the output. These inputs are in the form of
parameters. The parameters themselves are composed of the data type and the parameter name. The data
type restricts the values that can be passed to the function (int only allows Integer values, bool allows
Boolean values and so on) and the parameter name can be used like a regular variable under the function
body. This variable would be initialized with the value that is passed to the function when it is invoked
(called). A function can have any number of parameters each of which need to separated by a comma.
A parameter can have two variations - ref and out.
Example to get customer data and display customer data
#region CustomerClass
class Customer
{ #region Variables
int _custNo;
string _custName;
string _custAddress;
int _custAge;
#endregion
#region Methods
#region GetCustomerData
public void GetCustomerData()
{ Console.WriteLine("Enter Customer No,Customer name,Customer Address,Customer Age");
_custNo =int.Parse(Console.ReadLine());
_custName = Console.ReadLine();
_custAddress = Console.ReadLine();
_custAge =Convert.ToInt32(Console.ReadLine());
} #endregion
#region DisplayCustomerData
public void DisplayCustomerData()
{
Console.WriteLine("Customer No
is"+_custNo);
Console.WriteLine("Customer Name
is"+_custName);
Console.WriteLine("Customer Address
is"+_custAddress);
Console.WriteLine("Customer Age
is"+_custAge);
Console.ReadLine();
}
#endregion
#endregion
}
#endregion
#region MainClass
class Program
{
static void Main(string[] args)
{
//syntax for creating an object
//classname objname=new class name();
Customer obj = new Customer();
//call the method
//syntax for calling the method
//objname.methodname();
obj.GetCustomerData();
obj.DisplayCustomerData();
} }
#endregion
Concrete class: a class which supports inheritance ,polymorphism is called as a concrete class
Data members: the variables declared inside the class are called as data members
Types of data members
Instance data members: the data members whose memory is created when an instance object is created
Static data members: the data members whose memory allocated automatically when the class is loaded
before main method on the stack this data member declaration requires static keyword and they can be
accessible directly within the class and using class name in some other class
Syntax: <access specifier> static<data type> <variable>;
Constant data members : the data members which are static in nature and requires some rules at the
time of declaration
Constructor is a method in the class which gets executed when its object is created. Usually we
put the initialization code in the constructor. Whose task is to initialize the objects of its classes.
There is no need to write any explicit statements to involve the constructor method
A constructor doesnt have any return type even void also but method has a return type, hence it
not returns value
Types of constructors:
Default constructors:
#region Customer
class Customer
{
#region Variables
int _cNo;
string _cName;
string _custAddress;
int _custAge;
#endregion
#region Constructor
public Customer()
{
_cNo = 101;
_cName = "sunil";
_custAddress = "hyderabad";
_custAge = 23;
}
#endregion
#region Methods
public void GetCustomerData()
{
Console.WriteLine("customer no
is"+_cNo);
Console.WriteLine("customer name
is"+_cName);
Console.WriteLine("customer address
is"+_custAddress);
Console.WriteLine("cust age
is"+_custAge);
Console.ReadLine();
}
#endregion
}
#endregion
#region MainClass
class Program
{
static void Main(string[] args)
{
//created an object
Customer obj = new Customer();
//call the method
obj.GetCustomerData();
}
}
#endregion
class class2
{
static void Main(string[] args)
{
Employee e1 = new Employee();
e1.DisplayEmpdata();
Console.ReadLine();
}
}
This Keyword
This is a keyword which represents the current class.
This keyword acts like an object for a current class which can be used in the current class.
public Customer()
{
this._CustNo = 10;
this._CustName = "Anil";
this._CustAddress= "Hyderabad";
this._CustAge= 24;
}
Disadvantages of default constructor
Any no of objects might be created for class all objects data fields will store same set of values
To overcome this drawback we use parameterized constructor
parameterized constructor :
This constructor will accept parameters those values can be stored wit the data fields of the class
Parameterized constructor is used to store different set of values for each object we create for the
class
Rules to follow:
1. The no of arguments for every constructor should differ
2. If the no of arguments are same they should differ with type of arguments if the type of the args
are also same then they should differ with mode of the arguments
3. When more than one constructor is defined in a single class then it is called as constructor
overloading
Syn:
Public <class name>(.)
{
..
}
parameterized constructor
class Customer
{
int _CustNo;
string _CustName;
string _CustAddress;
int _CustAge;
public Customer(int _cno,string _cname,string
_cstaddress,int _cage)
{
this._CustNo = _cno;
this._CustName = _cname;
this._CustAddress = _cstaddress;
this._CustAge = _cage;
}
public void DisplayData()
{
Console.WriteLine(" CustNo is"+_CustNo);
Console.WriteLine("CustName
is"+_CustName);
Console.WriteLine("CustAddress
is"+_CustAddress);
Console.WriteLine("Cust Age
is"+_CustAge);
}
}
class Program
{
static void Main(string[] args)
{
Customer objcust1 = new
Customer(100,"Anil","Hyderabad",24);
Customer objcust2 = new Customer(200,
"Sunil", "Calcutta", 24);
objcust1.DisplayData();
objcust2.DisplayData();
Console.ReadLine();
}
}
STATIC CONSTRUCTOR
Static constructors are invoked only once during the execution of the program and can be used to
initialize the static variables.
This is a special constructor and gets called before the first object is created of the class. The time
of execution cannot be determined, but it is definitely before the first object creation.
There can be only one static constructor in the class.
The static constructor should be without parameters.
It can only access the static members of the class.
There should be no access modifier in static constructor definition.
Reason!!!
The call to the static constructor is made by the CLR and not by the object, so we do not need to
have the access modifier to it.
As it is going to be called by CLR, who can pass the parameters to it (if required). So, we cannot
have parameterized static constructor
Non-static members in the class are specific to the object instance so static constructor, if allowed
to work on non-static members, will reflect the changes in all the object instances, which is
impractical. So static constructor can access only static members of the class.
Static constructor:
A constructor which is used to initialize only static members of a class and which is
automatically called before any static member is accessible
Syntax:
Static <class name> ()
{
.
.
}
Rules to declare static constructor
1. It declaration should not include any access modifier
2. It should not include any arguments
3. A class can contain only one static constructor
#region Date
class Date
{
static int date, month, year;
static Date()
{
date = DateTime.Now.Day;
month = DateTime.Now.Month;
year = DateTime.Now.Year;
}
public static void DisplayData()
{
Console.WriteLine("date is:{0}-{1}{2}",date,month,year);
Console.ReadLine();
}
}
#end region
#region Program
class Program
{
static void Main(string[] args)
{
Date.DisplayData();
}
}
#end region
}
class Program
{
static void Main(string[] args)
{
A obj = new A();
}
}
Inheritance
Inheritance is the process of deriving the the base class members in to the derived class
whenever we are creating an object for derived class.
Derived class is also called as child class or subclass
Base class is also called as Parent class or super class
It enables easy maintenance of code by reusability.
Any changes made to the base class automatically changes the behavior of its subclasses.
Sample Inheritance
class BaseClass
{
public void Show()
{
Console.WriteLine("in Base Class Show method");
}
}
class DerivedClass:BaseClass
{
public void Display()
{
Console.WriteLine("in Derived class
Display method");
}
}
OUTPUT
class Program
{
static void Main(string[] args)
{
BaseClass obj1 = new BaseClass();
obj1.Show();
DerivedClass obj2 = new DerivedClass();
obj2.Show();
obj2.Display();
BaseClass obj3 = new DerivedClass();
obj3.Show();
// DerivedClass obj4 = new BaseClass();
} }
Types of Inheritance
Single Inheritance
Multi Level Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
It is a process of deriving the Base class members in to the Derived Class whenever we are
creating an object for Derived Class.
Here in the above example A is super class and B is Derived Class
The operator :is used to indicate that a class is inherited from another class.
#region College
class College
{
int _collegeNo;
string _CollegeName;
string _CollegeAddress;
string _CollegeLocation;
#region College
class College
{ int _cNo;
string _cName;
string _cAddress;
#region GetCollegeData
public void GetCollegeData()
{
Console.WriteLine("Enter
CollegeNo,CollegeName,CollegeAddress");
_cNo =
Convert.ToInt32(Console.ReadLine());
_cName = Console.ReadLine();
_cAddress = Console.ReadLine();
}
#endregion
#region DisplayCollegeData
public void DisplayCollegeData()
{ Console.WriteLine("College No is" +
_cNo);
Console.WriteLine("College Name is" +
_cName);
Console.WriteLine("College Address is" +
_cAddress);
}
#endregion
}
#endregion
#region Faculty
class Faculty : College
{
int _FacId;
string _FacName;
string _FacAddress;
int _FacAge;
#region GetFacultyData
public void GetFacultyData()
{
Console.WriteLine("Enter
FacId,FacName,FacAddress,FacAge");
_FacId =
Convert.ToInt32(Console.ReadLine());
_FacName = Console.ReadLine();
_FacAddress = Console.ReadLine();
_FacAge
=Convert.ToInt32(Console.ReadLine());
}
#endregion
#region DisplayFacultyData
public void DisplayFacultyData()
{
Console.WriteLine("FacId is"+_FacId);
Console.WriteLine("FacultyName
is"+_FacName);
Console.WriteLine("Faculty Address
is"+_FacAddress);
Console.WriteLine("Faculty Age
is"+_FacAge);
}
#endregion
}
#endregion
#region Salary
class Salary : Faculty
{
double Basic;
double HRA;
double DA;
double Gross;
#region College
class College
{ int _cNo;
string _cName;
string _cAddress;
#region GetCollegeData
protected void GetCollegeData()
{
Console.WriteLine("Enter
CollegeNo,CollegeName,CollegeAddress");
_cNo =
Convert.ToInt32(Console.ReadLine());
_cName = Console.ReadLine();
_cAddress = Console.ReadLine();
}
#endregion
#region DisplayCollegeData
protected void DisplayCollegeData()
{
Console.WriteLine("College No is" +
_cNo);
Console.WriteLine("College Name is" +
_cName);
Console.WriteLine("College Address is" +
_cAddress);
}
#endregion}
#endregion
#region Faculty
class Faculty : College
{
int _FacId;
string _FacName;
string _FacAddress;
int _FacAge;
#region GetFacultyData
protected void GetFacultyData()
{
base.GetCollegeData();
base.DisplayCollegeData();
Console.WriteLine("Enter
FacId,FacName,FacAddress,FacAge");
_FacId =
Convert.ToInt32(Console.ReadLine());
_FacName = Console.ReadLine();
_FacAddress = Console.ReadLine();
_FacAge
=Convert.ToInt32(Console.ReadLine());
}
#endregion
#region DisplayFacultyData
protected void DisplayFacultyData()
{
Console.WriteLine("FacId is"+_FacId);
Console.WriteLine("FacultyName
is"+_FacName);
Console.WriteLine("Faculty Address
is"+_FacAddress);
Console.WriteLine("Faculty Age
is"+_FacAge);
}
#endregion
}
#endregion
#region Salary
class Salary : Faculty
{
double Basic;
double HRA;
double DA;
double Gross;
Hierarchical Inheritance
class Parent
{
public void Car()
{
Console.WriteLine("This is car method");
}
public void Bike()
{
Console.WriteLine("This is Bike method ");
}
protected void Naclace()
{
Console.WriteLine("This is nacklace
method");
}
public void House()
{
Console.WriteLine("This is House
method");
}
}
class Son:Parent
{
}
class Daughter:Parent
{
public void GoldRing()
{
Base.Nacklace();
Console.WriteLine(this is Ring);
}
}
class Program
{
static void Main(string[] args)
{
Daughter obj = new Daughter();
obj.Bike();
obj.Car();
obj.House();
Son obj1 = new Son();
obj1.Bike();
obj1.Car();
obj1.House();
}
}
Multiple Inheritance
Interfaces
class Program
{
static void Main(string[] args)
{
A obj = new A();
((I1)obj).Show();
((I2)obj).Show();
}
}
interface IWritable
{
void Write(string s);
}
interface IReadable
{
string ReadLine();
}
interface IFile:IWritable,IReadable
{
void Open(string filename);
void Close();
}
class MyFile:IFile
{
private string filename;
public void Open(string filename)
{
this.filename = filename;
Console.WriteLine("opening file:
{0}",filename);
}
public string ReadLine()
{
return "reading a file from MyFile:" +
filename;
}
Hybrid Inheritance
Abstract class contain abstract methods but it must contain only declaration like interface
When a method is getting inherited by name abstract we need to declare the definition of the
method in a concrete class
Abstract methods are by default virtual in nature
So we need to keep override keyword in the abstract method body definition
For an abstract class method definition the access modifier must be public
If a method is declared as abstract and the class is not declared as abstract so it is wrong.i.e
concrete class must not contain abstract methods
When we create an object for a concrete class we can access the abstract methods
An abstract class can contain all the members of a class i.e
datafields,functions,constructors,destructors,properties,indexers and events.
Abstract classes can have abstract methods and normal methods
abstract class A
{
public void Show()
{
Console.WriteLine("in A class Show
method");
}
public abstract void Display();
}
class B:A
{
public override void Display()
{
Console.WriteLine("in B class Display
method");
}
}
class Program
{
static void Main(string[ ] args)
{
B obj = new B();
obj.Show();
obj.Display();
}
}
#region Employee
abstract class Employee
{
protected int _empNo;
protected string _empName;
protected string _eAddress;
protected int _eAge;
public abstract void GetEmpData();
public virtual void DisplayEmpData()
{
Console.WriteLine("employee ID is:-" +
_empNo);
Console.WriteLine("employee name is:-" +
_empName);
Console.WriteLine("emp address is:-" +
_eAddress);
Console.WriteLine("emp age is:-" +
_eAge);
}
}
#endregion
#region Manager
class Manager:Employee
{
int _CA;
int _Bonus;
public override void GetEmpData()
{
Console.WriteLine("Enter Manager
no,Name,address,Age,Ca");
_empNo
=Convert.ToInt32(Console.ReadLine());
_empName = Console.ReadLine();
_eAddress = Console.ReadLine();
_eAge =Convert.ToInt32(Console.ReadLine());
_CA =
Convert.ToInt32(Console.ReadLine());
_Bonus =
Convert.ToInt32(Console.ReadLine());
}
public override void DisplayEmpData()
{
Console.WriteLine("Manager ID is:"+_empNo);
Console.WriteLine("Manager Name is:"+_empName);
Console.WriteLine("CA is:-"+_CA);
Console.WriteLine("Bonus is:-"+_Bonus);
}
}
#endregion
#region MainClass
class Program
{
static void Main(string[] args)
{
Manager obj = new Manager();
obj.GetEmpData();
obj.DisplayEmpData();
}
}
#endregion
POLYMORPHISM
It is a process of defining multiple functionalities with same name either in single class or the base and
derived class.
Polymorphism in c#.net is classified in to three types
Overloading
Overriding
It is a process of defining multiple functionalities with same name but with different signature in
a single class.
Rules to work with overloading:
TYPES OF OVERLOADING
METHOD OVERLOADING
CONSTRUCTOR OVERLOADING
METHOD OVERLOADING
Example:
#region ClassA
class A
{
public void Show()
{
Console.WriteLine("this is Show1");
}
public void Show(int a)
{
Console.WriteLine("the value of a is"+a);
}
public void Show(int a,int b)
{
int c =Convert.ToInt32(a + b);
Console.WriteLine("the value of a+b
is"+c);
}
}
#endregion
CONSTRUCTOR OVERLOADING
#region StudentClass
class Student
{
#region Variables
int _studNo;
string _studName;
int _studAge;
string _studAddress;
#endregion
#region MainClass
class Program
{
static void Main(string[] args)
{
A obj = new A();
obj.Show();
obj.Show(10);
obj.Show(10, 20);
Console.ReadLine();
}
}
#endregion
#region DefaultConstructor
public Student()
{
this._studNo = 101;
this._studName = "sunil";
this._studAge = 23;
this._studAddress = "hyd";
}
#endregion
#region CopyConstructor
public Student(Student obj2)
{
this._studNo = obj2._studNo;
this._studName = obj2._studName;
this._studAge = obj2._studAge;
this._studAddress = obj2._studAddress;
}
#endregion
#region Methods
public void GetData()
{
Console.WriteLine("Enter
Studno,StudName,studAge,StudAddress");
_studNo =
Convert.ToInt32(Console.ReadLine());
_studName =Console.ReadLine();
_studAge
=Convert.ToInt32(Console.ReadLine());
_studAddress = Console.ReadLine();
}
class Program
{
static void Main(string[] args)
{
B obj = new B();
obj.Show();
}
}
Complie-Time Warning
When we compile the above program, the compiler
will show a warning, since we try to hide a Base
class data member inside the Derived class. By
using the keyword new along with the data member
declaration inside the Derived class, it is possible to
suppress this compiler warning.
class A
{
public void Show()
{
Console.WriteLine("A class Show()");
}
}
class B:A
{
public void Show()
{
Console.WriteLine("B class Show()");
}
}
class Program
{
static void Main(string[] args)
{
A obj = new B();
obj.Show();
// B obj = new A();
}
}
Output:A class Show()
class Program
{
static void Main(string[] args)
{
A obj = new B();
obj.Show();
// B obj = new A();
}
}
Output:B class Show()
When we want to override a virtual method polymorphically inside a Derived class, we have to
use the keyword override along with the method declaration.
In C#, a Base class reference can hold an object of the Derived class and when it invokes the
methods, it will invoke always the Derived class methods, if you already override that method
inside the Derived class by using the override keyword. Also the Base class method must declare
using the keyword virtual. This is known as Polymorphism in C#.
Override keyword
Overriding is the action of modifying or replacing the implementation of the parent class with a
new one. Parent classes with virtual or abstract members allow derived classes to override them.
Example:
#region Customer
class Customer
{
protected int _custNo, _custAge;
protected string _custName;
protected string _custAddress;
public virtual void GetCustData()
{
Console.WriteLine("Enter
custno,custname,custaddress,and age:-");
_custNo =
Convert.ToInt32(Console.ReadLine());
_custName = Console.ReadLine();
_custAddress = Console.ReadLine();
_custAge =
Convert.ToInt32(Console.ReadLine());
}
public virtual void DispalyCustomerData()
{
Console.WriteLine("Customer id is" +
_custNo);
Console.WriteLine("customer name is" +
_custName);
Console.WriteLine("customer address is" +
_custAddress);
Console.WriteLine("customer age is" +
_custAge);
}
}
#endregion
#region Supplier
class Supplier : Customer
{
int _CA, _Bonus;
public override void GetCustData()
{
Console.WriteLine("enter
Managerid,Name,CA,Bonus"
_custNo =
Convert.ToInt32(Console.ReadLine());
_custName = Console.ReadLine();
_CA =
Convert.ToInt32(Console.ReadLine());
_Bonus =
Convert.ToInt32(Console.ReadLine());
}
public override void DispalyCustomerData()
{
Console.WriteLine("manager id is:-" +
_custNo);
Console.WriteLine("manager name is:-" +
_custName);
Console.WriteLine("manger CA is:-" +
_CA);
Console.WriteLine("manager Bonus is:-" +
_Bonus);
}
}
#endregion
#region Program
class Program
{
static void Main(string[] args)
{
Customer c = new Customer();
c.GetCustData();
c.DispalyCustomerData();
Console.ReadLine();
}
} #endregion
PROPERTIES
In C++ and Java, when creating the member variables of a class, programmers usually "hide"
these members in private sections (C++) or create them as private (Java). This technique makes sure that
a member variable is not accessible outside of the class so that the clients of the class cannot directly
influence the value of the member variable. If you create a member variable as private but still want other
classes to access or get the value of such a field, you must then create one or two "accessories" must pass
through to access the field.
This private field cannot be accessed by an outside class. To let the outside classes access this
variable, you would/can create a property.
A property is a special data member of a class which is used for setting and getting the values for
private data members of the class.
The properties contain two accessors
Set Accessor-------used to assign a value
Get Accessor..used to return a value
Properties are called smart fields of a class.
Accessor: it is a member of a property which is used to provide accessibility (reading and writing ) of
the data fields.
Set Accessor: it is used to write the data into data fields of the class.
Set accessor will have a fixed and default variable named as value.
Any data we write will come and store by default into value variable.
GetAccessor: this is used to read data from data fields of the class.
Syntax for properties:
Types of properties
Read Only
Write Only
Read-Write
Read Only
This property is used to read the data from the data field of a class.
To read the data from the data fields of the class we use get accessor.
Syntax for Read Only property
<Access modifier><datatype><propertyname>
{
get
{
return variable name;
}
}
#region itemnameproperty
public string itemname
{
get
{
return _itemName;
}
}
#endregion
#region itempriceproperty
public double itemprice
{
get
{
return _itemPrice;
}
}
#endregion
#region SizeProperty
public double size
{
get
{
return _size;
}
}
#endregion
#endregion
#region Constructor
public StoreDepartment(int ino,string
iname,double iprice,double isize)
{
_itemNo = ino;
_itemName = iname;
_itemPrice = iprice;
_size = isize;
}
#endregion
}
#endregion
}
StoreDepartment store=new
StoreDepartment(itno,itname,itprice,itsize);
Console.WriteLine("------------------------");
Console.WriteLine("------------------------");
Console.WriteLine("item no is"+store.itemno);
Console.WriteLine("item name
is"+store.itemname);
Console.WriteLine("itemprice
is"+store.itemprice);
Console.WriteLine("item size
is"+store.size);
Console.WriteLine("total amount
is"+store.itemprice*store.size);
Console.WriteLine("------------------------");
Console.WriteLine("------------------------");
Console.ReadLine();
}
}
#endregion
}
Write only
This property is used to write the data from the data field of a class.
To write the data from the data fields of the class we use set accessor.
Syntax for set accessor
<Access modifier><datatype><propertyname>
{
set
{
variable name=value;
}
}
A property will not allocate memory to store data.it is used to transfer the data
Properties must not have any arguments
Properties will not have any variables
When we are declaring a property datatype of the property must and should be same with
datatype of the variable
Read-Write Property
This property is used to read and write the data from the data field of a class.
Read write property consists set and get accessor.
Example:
#region StudentClass
class Student
{
#region Variables
int _studentNo;
string _studentName;
int _studentAge;
double _marksinEnglish;
double _marksinMaths;
double _marksinScience;
double _obtainedMarks;
double _percentage;
double _totalMarks=300;
#endregion
#region Properties
#region studentNo
public int studentNo
{
set
{
_studentNo = value;
}
get
{
return _studentNo;
}
}
#endregion
#region StudentName
public string StudentName
{
set
{
_studentName = value;
}
get
{
return _studentName;
}
}
#endregion
#region studentage
public int studentage
{
set
{
_studentAge = value;
}
get
{
return _studentAge;
}
}
#endregion
#region marksinmaths
public double marksinmaths
{
set
{
if (value >= 0 && value <= 100)
{
_marksinMaths = value;
}
else
{
_marksinMaths = 0;
}
}
get
{
return _marksinMaths;
}
}
#endregion
#region marksinenglish
public double marksinenglish
{
set
{
if (value >= 0 && value <= 100)
{
_marksinEnglish = value;
}
else
{
_marksinEnglish= 0;
}
}
get
{
return _marksinEnglish;
}
}
#endregion
#region marksinscience
public double marksinscience
{
set
{
if (value >= 0 && value <= 100)
{
_marksinScience = value;
}
else
{
_marksinScience= 0;
}
}
get
{
return _marksinScience;
}
}
#endregion
#region obtainedmarks
public double obtainedmarks
{
set
{
_obtainedMarks= value;
}
get
{
return _obtainedMarks;
}
}
#endregion
#region percentage
public double percentage
{
set
{
_percentage = value;
}
get
{
return _percentage;
}
}
#endregion
#region totalmarks
public double totalmarks
{
set
{
_totalMarks = value;
}
get
{
return _totalMarks;
}
}
#endregion
#endregion
#region Methods
public void CalculatetotalMarks()
{
obtainedmarks = _marksinEnglish +
_marksinMaths + _marksinScience;
}
#region PercentageOfMarks
public void Calculatepercentage()
{
percentage = (double)_obtainedMarks /
_totalMarks * 100;
}
#endregion
#endregion
}
#endregion
#region MainClass
class Program
{
static void Main(string[] args)
{
#region Variables
int _stNo;
string _stName;
int _stAge;
double _minEnglish;
double _minMaths;
double _minScience;
double _omarks;
double _percent;
#endregion
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("STUDENT PROGRESS
REPORT");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("ENTER STUDENT
ROLLNO:");
_stNo =int.Parse(Console.ReadLine());
Console.WriteLine("ENTER STUDENT
ANME:");
_stName = Console.ReadLine();
Console.WriteLine("ENTER STUDENT
AGE:");
_stAge = int.Parse(Console.ReadLine());
Console.WriteLine("ENTER STUDENT MAKS IN ENGLISH:");
_minEnglish = double.Parse(Console.ReadLine());
Console.WriteLine("ENTER STUDENT MAKS IN MATHS:");
_minMaths = double.Parse(Console.ReadLine());
Console.WriteLine("ENTER STUDENT MAKS IN SCIENCE:");
_minScience = double.Parse(Console.ReadLine());
Student obj = new Student();
obj.studentNo = _stNo;
obj.StudentName = _stName;
obj.studentage = _stAge;
obj.marksinenglish = _minEnglish;
obj.marksinmaths = _minMaths;
obj.marksinscience=_minScience;
obj.CalculatetotalMarks();
_omarks = obj.obtainedmarks;
obj.Calculatepercentage();
_percent=obj.percentage;
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("STUDENT TOTALMARKS IS:"+_omarks);
Console.WriteLine("TOTAL PERCENTAGE OF MARKS IS:"+_percent+"%");
Console.ReadLine();
}
}#endregion
READ-WRITE
namespace ConsoleApplication13
{
#region PersonClass
class Person
{
#region Variables
float _height;
float _weight;
string _name;
int _age;
char _gender;
#endregion
#region Properties
public float Height
{
set
{
_height = value;
}
get
{
return _height;
}
}
public float Weight
{
set
{
_weight = value;
}
get
{
return _weight;
}
}
Indexers
If we declared an array as a member variable of a class, to access the elements of that member,
we had to use an instance of the class, followed by the period operator, followed by the member variable
applied with the square brackets. Instead of accessing each element through its member variable, you can
create a type of property referred to as an indexer.
Syntax of indexers:
EXAMPLE
namespace INDEXERS
{
#region Sample
class Sample
{
float[] _temp=new
float[5]{10.0F,20.3F,30.9F,43.7F,39.8F};
public float this[int index]
{
get
{
return _temp[index];
}
set
{
_temp[index] = value;
}
}
}
#endregion
#region MyRegion
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample();
obj[2] = 77.6F;
Console.WriteLine(obj[2].ToString());
}
Console.ReadLine();
}
#endregion
}
ARRAYS
An array is a userdefined reference type data type used to store multiple values using same name.
Each array location of the array is identified using its index value.
Always the index start with 0 and end with size-1
First index of the array is known as lower bound and the last index of the array is known as upper
bound.
single-dimensional
dimensional arrays
multidimensional
imensional arrays or rectangular arrays
jagged arrays
mixed arrays.
Assigning values
Each element of the array can be accessed by specifying their index along with the ArrayName.
ArrayName[index] = value;
Example:Marks[5] = 99;
Values can also be assigned during declaration as follows:datatype[] ArrayName = {value1, value2, value3 and so on};
Example:int[] Marks = {100, 13, 69, 99};
Using this process implicitly sets the size for the array. In this case it would be 4. The elements can be
accessed by their indexes starting from 0 to 3. Note: In C# Index always starts at 0.
Using the following is equivalent to using the above line of code.
int[] Marks =new int[4] {100, 13, 69, 99};
Foreach statement
This statement is explicitly used to traverse through arrays. The benefit of using foreach over the
normal for statement is that it is not needed to check the size of the array while using the former.
Syntax:foreach(type identifier in expression)
{
statement 1;
statement 2;
....
}
EX:For statement
class Program
{
static void Main(string[] args)
{
string[] student_names =new string[]{ "kanna",
"sunil", "anil", "kareem" };
Declaration
The number of commas ( , ) inside the square brackets [ ] should be one less than the number of
dimensions required for the array.
Example Usage:int [ , ] Numbers;
Initialization
int[,] Numbers = new int[3, 4]
{
{10, 20, 30,40},
{50, 60, 70,80},
{90, 100, 110,120}
};
Assigning Values
Values can be assigned as:-
Numbers[0, 2] = 30;
class Program
{
static void Main(string[] args)
{
int[,] A = new int[3, 4] { { 10, 20, 30, 40 },
{ 50, 60, 70, 80 }, { 90, 100, 110, 120 }};
for (int R = 0; R < 3; R++)
{
Another Example
class Program
{
static void Main(string[] args)
{
#region MULDimeArray Syntax-1
int[,] even_nos = new int[3, 4];
even_nos[0, 0] = 2;
even_nos[0, 1] = 4;
even_nos[0, 2] = 6;
even_nos[0, 3] = 8;
even_nos[1, 0] = 10;
even_nos[1, 1] = 12;
even_nos[1, 2] = 14;
even_nos[1, 3] = 16;
even_nos[2, 0] = 18;
even_nos[2, 1] = 20;
even_nos[2, 2] = 22;
even_nos[2, 3] = 24;
Another example
class Program
{
static void Main(string[] args)
{
#region MulDimarray-2
float[,] float_nos = new float[3, 3] { { 10, 20, 30 },
{ 40, 50, 60 }, { 70, 80, 90 } };
for (int i = 0; i < float_nos.GetLength(0); i++)
{
for (int j = 0; j <float_nos.GetLength(1); j++)
{
Console.Write(float_nos[i,j]+"\t");
}
Console.WriteLine();
}
Console.ReadLine();
#endregion
}
}
#endregion
Jagged Array
A[0][1].>20 A[0][2].>30
A[1][0].>40
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
int[]A1=new int[3]{10,20,30};
int[] A2 = new int[4] { 40, 50, 60, 70 };
int[][] A = new int[][]{ A1, A2 };
Console.WriteLine("elements of jagged
array");
COLLECTIONS
using System. Collections;
It is the namespace which is used for providing some predefined classes and interfaces to
introduce data structures in .NET.
Array List
Stack
Queue
Hash Table
Sorted List
Array List
Arraylist will accept any datatype
The length of array is fixed but arraylist length will automaticaly set dynamically
This class is used for maintaining different types of information with variant type, dynamic size
and provides some methods to overcome all the drawbacks of arrays.
Syntax for Array List:
ArrayList Ar = new ArrayList();
Methods in ArrayList Class
Add():this method is used for adding the elements into arraylist
Insert():this method is used to insert the elements in arraylist
Remove():this method is used to remove an elemt from arraylist
Clear():this method is used to clear
Reverse():this method is used to arrange the elements of array in reverse order
Sort():this method is used to sort the elements of array in ascending order.
The benefit of using Foreach over the normal for statement is that it is not needed to check the
size of the array while using the former
syntax
foreach (var item in collection)
{
}
Example to Add( )in Arraylist
class Program
{
static void Main(string[] args)
{
ArrayList Ar = new ArrayList();
Ar.Add(10);
Ar.Add(20);
Ar.Add(30);
Ar.Add(40);
Ar.Add(50);
Ar.Add(60);
Ar.Insert(3, 90);
Ar.Remove(20);
Ar.RemoveAt(2);
Ar.Sort();
Ar.Clear();
foreach (object Ar1 in Ar)
{
Console.WriteLine(Ar1);
}
Console.ReadLine();
}
obj1 = Console.ReadLine();
obj2 = Console.ReadLine();
Ar.Add(obj1);
Ar.Add(obj2);
foreach (object Ar1 in Ar)
{
Console.WriteLine(Ar1);
}
Console.ReadLine();
}
}#endregion
STACK
This class is used for maintaining variant type of information with a dynamic size by using
LIFO(Last in First Out)
Ex :Dining Plates.
It performs insertion and deletions only from one end.
Methods :
Push():is used to insert the record
Pop():it is used to remove the inserted record
#region Stack
class Program
{ static void Main(string[] args)
{
Stack st = new Stack();
st.Push(10);
st.Push(20);
st.Push(30);
st.Push(40);
st.Push(50);
st.Push(60);
st.Pop();
St.Clear();
foreach (object st1 in st)
{
Console.WriteLine(st1.ToString());
}
Console.ReadLine(); }
}
#endregion
QUEUE
It is used for maintaining the information with dynamic size and variant type in FIFO
In queue the insertions will be from one end and deletions from the other end
Methods:
Enquee():used to insert a value
Dequee():used to remove a value
#region Queue
class Program
{
static void Main(string[] args)
{
Queue qu = new Queue();
qu.Enqueue(10);
qu.Enqueue(20);
qu.Enqueue(30);
qu.Enqueue(40);
qu.Dequeue();
qu.Clear();
Hash Table
This class is used for maintaining the information in key and value pair format.
It is used for fast searching and accessing the elements.
Hash table is used to display the data randomly
Hash Table is implemented from the interfaces like Idictionary,Icollection,Ienumerable,
DictionaryEntry. C# uses an object of this type when using the foreach loop with Hashtables.
That's because it automatically returns both the Key and the Value. IDictionaryEnumerator
etc
#region Hashtable
class Hashtable
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(0, 25);
ht.Add(10, 250);
ht.Add(67, 980);
ht.Add(45, 655);
ht.Add(70, 225);
Sorted List
It is used for maintaining the information in key and value pair format as a sorted with key
#region Hashtable
class A
{
static void Main(string[] args)
{
SortedList st = new SortedList();
st.Add(10, 456);
st.Add(0, 56);
st.Add(30, 6);
st.Add(50, 356);
st.Add(63, 63);
st.Add(75, 466);
st.Add(91, 896);
EXCEPTIONS
We can overcome three types of errors in our visual studio editor
1. Syntax Errors
2. Compilation Errors
3. Runtime Errors
Syntax Errors
If the user is typing any syntax then the error will occur.
These errors can be identified when we type the syntax and can be rectified immediately before
execution only.
These errors will not cause any harm to the program which can be easily rectified.
Compilation Errors
These errors will occur at the time of compiling the code.
Like assigning the wrong data type to a variable
Creating an object for abstract class or interface
Missing the no of arguments for a method, missing return types to a method etc
These errors can be rectified while compiling the code and can be rectified easily
These errors will not cause any harm to the program which can be easily rectified.
Runtime Errors
Exceptions
Exceptions cant be identified whenever we type the code and compile the code so we cant rectify
the exceptions.
Exceptions will cause abnormal termination of the program execution as we cannot rectify the
exceptions we can handle the exceptions to avoid abnormal termination of the program
Methods to Handle the Exceptions
Logical Implementation
Try-Catch Implementation
On-error go to implementation
Logical Implementation
int a, b, c;
private void button1_Click(object sender,
EventArgs e)
{
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
if (b == 0)
{
label1.Text = "second no must not be zero";
}
else
{
c = a / b;
textBox3.Text = c.ToString();
}
}
All the exceptions may not be possible to handle using logical implementation then we use Try-Catch
Implementation
Try-Catch Implementation
Syntax for try-catch
try
{
----------------------statements
}
catch (Exception class object)
{
----------------------statements
}
finally
{
---------statements
}
Try Block
It contains all the statements in which there is a possibility of error occurrance.
A Try block should be followed by minimum one catch block.
A try block can contain one or more catch blocks.
Catch Block
Catch block contains all the statements that what we need to do whenever an exception is raised
Finally
The code that is written in finally block will be executed even if the exception occurs
EXCEPTION CLASS
MS has provided different exception classes to handle the exceptions raised by different reasons.
Exception is the super class for all the exceptions
Properties:
Message: this property stores about the reason why error has been occurred
System.ArithmeticException-A base class for exceptions that occur during arithmetic operations,
such as System.DivideByZeroException
System.ArrayTypeMismatchException-Thrown when a store into an array fails because the actual
type of the stored element is incompatible with the actual type of the array.
System.DivideByZeroException-Thrown when an attempt to divide an integral value by zero
occurs.
System.IndexOutOfRangeException-Thrown when an attempt to index an array via an index that
is less than zero or outside the bounds of the array.
System.InvalidCastExceptionThrown when an explicit conversion from a base type or interface to
derived types fails at run time.
System.MulticastNotSupportedException-Thrown when an attempt to combine two non-null
delegates fails, because the delegate type does not have a void return type.
System.NullReferenceException-Thrown when a null reference is used in a way that causes the
referenced object to be required.
System.OutOfMemoryException-Thrown when an attempt to allocate memory (via new) fails.
System.OverflowException-Thrown when an arithmetic operation in a checked context
overflows.
Divide by Zero Exception predefined exception
int a, b, c;
private void button1_Click(object sender,
EventArgs e)
{
try
{
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
c = a / b;
textBox3.Text = c.ToString();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
}
textBox3.Text = c.ToString();
}
catch (DivideByZeroException)
{
MessageBox.Show("denominator must not be
zero");
}
IndexOutOfRangeException
class Program
{
static void Main(string[] args)
{
try
{
int[] Ar = new int[5];
for (int i = 0; i < 10; i++)
{
Ar[i] = i;
}
}
catch (Exception e1)
{
Console.WriteLine(e1.Message);
}
}
}
SqlException
class Program
{
static void Main(string[] args)
{
try
{
SqlConnection con = new SqlConnection("user
id=sa;password=1234;database=emp;data
source=localhost");
con.Open();
con.Close();
}
catch (SqlException)
{
Console.WriteLine("invalid user credentials");
}
}
}
try
{
SqlConnection con = new SqlConnection
("user id=sa;password=1234;database=emp;data
source=localhost");
con.Open();
int[] Ar = new int[5];
for (int i = 0; i < 10; i++)
{
Ar[i] = i;
}
con.Close();
}
catch (IndexOutOfRangeException e2)
{
Console.WriteLine(e2.Message);
}
catch (SqlException)
{
Console.WriteLine("invalid user
credentials");
}
Logical Exception
private void Form1_Load(object sender, EventArgs
e)
{
SqlConnection con = new
SqlConnection("user
id=sa;password=1234;database=emp;data
source=localhost");
try
{ con.Open();
con.Close();
}
catch (SqlException)
{
MessageBox.Show("invalid
credentials");
}
finally
{
if (con.State==ConnectionState.Open)
{
con.Close();
}
}
}
Format Exception
private void button1_Click(object sender,
EventArgs e)
{
try
{
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
c = a / b;
textBox3.Text = c.ToString();
}
catch (FormatException)
{
MessageBox.Show("enter only
numbers");
}
}
Overflow Exception
catch (Overflow Exception)
{
MessageBox.Show("Enter numbers between " + Int32.MinValue.ToString() + " and " +
Int32.MaxValue.ToString());
}
Classifications of Exceptions
System Exceptions : All .NET defined exceptions are examples of System Exceptions.
DivideByZeroException,OverflowException etc.. are examples of System Exceptions. All
predefined .NET exceptions derive directly or indirectly from SystemException class.
SystemException class derives from Exception class.
Application Exceptions : If none of the exceptions available in .NET, are useful for your program,
you can create userdefined exceptions. Userdefined exceptions usually derive from
ApplicationException class. ApplicationException class derive from Exception class
ApplicationException
class UserDefinedException:ApplicationException
{
public UserDefinedException()
{
Console.WriteLine("userdefined
exception");
}
}
class Program
{
static void Main(string[] args)
{
try
{
throw new UserDefinedException();
}
Note
All exceptions directly or indirectly derive from System. Exception base class.
It is a compile time error to have try block in isolation. A try block should be followed by a catch
or finally block.
A single try block can have multiple catch blocks but only one finally block.
We use the throw keyword to raise exceptions programmatically.
//Console.WriteLine(File.ReadAllText("D:\\ABC.txt"));
#endregion
#region get the folders in adirectory
//DirectoryInfo dir = new DirectoryInfo("D:\\6AM");
//DirectoryInfo[] Ar = dir.GetDirectories();
//for (int i = 0; i < Ar.Length; i++)
//{
// Console.WriteLine(Ar[i].Name);
//}
#endregion
#region directory history
//DirectoryInfo dirobj = new DirectoryInfo("D:\\6AM");
//Console.WriteLine("---directory info---");
//Console.WriteLine("directory full name is:" + dirobj.FullName);
//Console.WriteLine("directory name is:" + dirobj.Name);
//Console.WriteLine("directory parent " + dirobj.Parent);
//Console.WriteLine("creation time" + dirobj.CreationTime);
//Console.WriteLine("root is" + dirobj.Root);
#endregion
#region GetBmpinformation
//Console.WriteLine("directory bmpinfo");
//DirectoryInfo dirobj = new DirectoryInfo("D:\\");
////to get all files with bmp extension
//FileInfo[] bitmapfiles = dirobj.GetFiles("*.bmp");
////how many were found
//Console.WriteLine("founf {0} *.bmp files \n",bitmapfiles.Length);
//foreach (FileInfo f in bitmapfiles)
//{
// Console.WriteLine( "****************************\n");
//{
// Console.WriteLine("name is:"+d.Name);
// Console.WriteLine("type is:"+d.DriveType);
// //check to see if the drive is mounted
// Console.WriteLine("free space is "+d.TotalFreeSpace);
// Console.WriteLine("format is:"+d.DriveFormat);
// Console.WriteLine("label is:"+d.VolumeLabel);
//}
#endregion
#endregion
#region FileInfoClass
FileInfo f = new FileInfo("D:\\6AM\\hello.txt");
FileStream fs = f.Create();
fs.Close();
FileInfo f2 = new FileInfo("D:\\6AM\\hello.txt");
FileStream fs2 = f2.Open(FileMode.Open);
Console.WriteLine(fs2);
fs2.Close();
#endregion
OVERVIEW
Windows Communication Foundation takes many existing communication technologies, such as Web
Services, Windows Remoting, Microsoft Message Queuing, and abstracts them into a single technology.
In most cases, this simplifies the way you communicate with other applications. It also allows you to
communicate with other applications without being coupled to a specific technology. Therefore, you
could use Web Services over SOAP to begin with, and later move to remote procedure calls (RPC)
without changing your code, just the configuration of WCF.
THE BASICS
There are a few basic tasks when creating a WCF service. The basic tasks that must be performed are, in
order:
1. Define the service contract. A service contract specifies the signature of a service, the data it
exchanges, and other contractually required data.
2. Implement the contract. To implement a service contract, create the class that implements the
contract and specify some custom behaviors that the runtime should have.
3. Configure the service by specifying endpoint information and other behavior information.
4. Host the service in an application.
5. Build a client application.
EXAMPLE
To display a step-by-step enactment of the above steps, lets define a web service that reports the
current date/time:
1.1 DEFINE A SERVICE CONTRACT
First, lets create a project to house our service contract. Lets call it
WCFDateTime.Service.
Then, lets define an interface that represents the service were going to provide. In this case,
lets call it IDateTimeService.
public interface IDateTimeService
{
}
We need to add a method to our service that will return the current date/time:
public interface IDateTimeService
{
DateTime GetCurrentDateTime();
}
Now, we need to decorate our code with attributes so that WCF will recognize our interface and
its methods. Namely, we will add the following attributes:
ServiceContractAttribute
o
OperationContractAttribute
o
using System.ServiceModel;
[ServiceContract]
public interface IDateTimeService
{
[OperationContract]
DateTime GetCurrentDateTime();
}
In order to use the above attributes, youll need to add a reference to the
System.ServiceModel assembly. The service contract is now ready to be used.
Now we need to configure our service so it can be consumed by client applications. The
simplest way to accomplish this is by adding an application configuration file (app.config or
web.config) to the WCFDateTime.Server project:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="WCFDateTime.Server.DateTimeService">
<endpoint
address="http://localhost:8081/DateTimeService"
binding="wsHttpBinding"
contract="WCFDateTime.Service.IDateTimeService" />
</service>
</services>
</system.serviceModel>
</configuration>
Now that WCF has been configured, the simplest way to host this service is to create a Console
Application and use the ServiceHost class. First, add a reference to the
System.ServiceModel assembly. Then, In the program.cs file of
WCFDateTime.Server, do the following:
using System.ServiceModel;
namespace WCFDateTime.Server
{
class Program
{
static public void Main(string[] args)
{
// Get a host for our service
ServiceHost serviceHost = new ServiceHost(
typeof(DateTimeService)
);
// Open the service host to start listening for incoming requests
serviceHost.Open();
// The service can now be accessed
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
By simply running this application, we expose our service so that client applications can use it.
To build a client application, we must create a new project for it. Lets call it
WCFDateTime.Client, and make it a Console Application as well.
Now, we need to add an Application Configuration file, and give it some settings that will allow
us to connect to the service we just created:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<client>
<endpoint
address="http://localhost:8081/DateTimeService"
binding="wsHttpBinding"
contract="WCFDateTime.Service.IDateTimeService"
name="MyDateTimeService">
</endpoint>
</client>
</system.serviceModel>
</configuration>
Now that our weve configured our WCF client, we can connect to it. There are two ways to
connect to the WCF service we previously created:
1. Client proxy generation
2. Channel factories
Most Microsoft articles will point you in the direction of using client proxies; however, for our
purposes, channel factories are quicker to implement and more robust in a
Model/View/Presenter architecture.
Your client application is now ready to run! Simply start the WCFDateTime.Server
application, and once its running, run the WCFDateTime.Client application to see it work!
WCF
1.Introduction
The aim of this article is to explain the basics of WCF in a manner as simple as possible.It is
assumed that the reader doesnt know anything about WCF or .NET 3.0, however he/she is
expected to know .NET 2.0 and/or simple facts like what is a web service.While writing this
article (or for any other) I always try to avoid difficult technical words, which may confuse the
reader. I have tried to put it in as simple words as possible.At the end of this article, I would
hope you understand at least some of the key WCF areas and possibly be inspired enough to try
out a project on your own.
2.Contents
1. Introduction
2. The most suitable reader for this article.
3. Prerequisites
4. A brief overview of demo service
5. Explanations of fundamentals involved
6. The demo Service with code
7. Conclusion
3. Prerequisites
To run the code supplied with this article you need to install .NET 3.0 API available with Visual
Studio 2008.
In this demo WCF service we are trying to carry out the following functionality:
a) Create a service
b) Host the service
c) Create a client for the service
d) Let the client interact with the service.
To achieve the above functionality we will create three inter related assemblies as mentioned below:
a) SampleService.dll this is the actual WCF service that allows clients to connect
b) SampleHost.dll this is the dll that hosts WCF service, SampleService.dll
c) SampleClient.dll this is the client assembly which communicates with SampleService.dll.
Assuming that the reader has no Background in WCF, there are a number of key concepts that
needs to be explained in order for the full application to be understood.
So I will just explain each of these a little bit at a time, so that the final application will be a little
easier to understand.
Key Concepts:
a) What is WCF?
WCF stands for Windows Communication Foundation.
WCF is advanced API (Application Programming Interface) for creating distributed
applications using .NET framework.
It is introduced in .NET 3.0.
Distributed system in its simplest form is two executable running and exchanging data.
WCF API is found in System.ServiceModel namespace.
WCF is based on basic concepts of Service oriented architecture (SOA)
ii) Bindings: This includes the type of network protocol used by the
Service. For Example HTTP, TCP/IP or others.
iii) Contracts: This is in fact the methods exposed by the WCF service.
Before I start, I would like to remind you again that this is the simplest of WCF service only for
understanding purpose. In real world you might have to build/face much more complicated WCF
service.
To understand the service better we will build the service as a c# class library project. Follow the
following steps:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SampleService
{
public class Class1
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace SampleServiceLib
{
public class SampleService
{
}
}
iv) At this point the project will not build, so please add a reference to
System.Service Model.
For this, Go to solution Explorer ,Right click on the reference Add Reference .NET
Tab Select System.ServiceModel OK.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.ServiceModel;
namespace SampleServiceLib
{
[ServiceContract]
public interface IAnswer
{
[OperationContract]
string ObtainAnswer(string Question);
}
}
viii) Save the sample service Project by File Save All. Then build it so that you will get a
SampleSevice.dll in its bin\release directory.
A WCF host may be IIS (Internet Information Server) , Windows Service, A console application
etc.The simplest of them is a console application host. So we will demonstrate that here.
Follow the following steps:
i) Open Visual Studio 2008
ii) Select Create ProjectC# Console Application name it Sample Host
iii) From Solution Explorer,Add the reference of System.ServiceModel to this project as before
and
iv) also add the reference of SampleServiceLib.dll from SmpleService Class library project you
created before by addreference Browse Tab Browse to the SampleServiceLib.dll in the project
SampleServices Bin/release folder.
v) Open its Program.cs file and add the following two namespace to the
Using Section.
Using System.ServiceModel
Using SampleServiceLib
vi)
Build the project successfully.
vii)
Add the following console.Writeline codes to program.cs so that the final Program.cs
Should look Like as below.
using
using
using
using
using
using System;
System.Collections.Generic;
System.Linq;
System.Text;
System.ServiceModel;
SampleServiceLib;
namespace SampleHost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Sample Host of Sample Service is
running....");
using (ServiceHost servicehost = new
ServiceHost(typeof(SampleService)))
{
servicehost.Open();
Console.WriteLine("The SampleService is ready now...");
Console.WriteLine("Press enter to terminate the
SampleService...");
}
Console.ReadLine();
}
}
}
Add the code inside the configuration tag of app.cofig so that the final app.cofig
<services>
<service name="SampleServiceLib.SampleService"
behaviorConfiguration="SampleServiceMEXBehavior">
<endpoint
address="http://localhost:8080/SampleService"
binding="basicHttpBinding"
contract="SampleServiceLib.IAnswer"></endpoint>
<host>
<baseAddresses>
<add
baseAddress="http://localhost:8080/SampleService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SampleServiceMEXBehavior" >
</system.serviceModel>
</configuration>
x)
Build the Service host application and run it. You should get a console Window while host
is running.
c)
Before building a client you need to build a proxy of the service which the client will use to interact
with the service.
A proxy is nothing but a .cs file and a .config file generated by a tool called svcutil.exe using your
service Sampleservice.dll
Steps to create the Proxy:
i) Create a Proxy folder in your c:\ drive.
ii) Search for the svcutil.exe file on your computer and copy it to the Proxy folder.
iii) Copy the dll of the service you created (sampleservice.dll) to this Proxy folder.
iv) Go to Start Run cmd
v) On the command prompt change the directory to Proxy folder.
vi) Run the following command
C:\ Proxy svcutil.exe SampleService.dll
This will create a few files in the current directory like
.wsdl, .xsd etc
vii) The run the following command
C:\ Proxy svcutil.exe *.wsdl *.xsd /language:C#
/out:SampleProxy.cs /config:app.config
It will create two files in the Proxy folder
SampleProxy.cs and app.config.
These are your proxy files to be used in the Client.
viii) Open the SampleProxy.cs file, it has the AnswerClient class which has the ObtainAnswer
Method from SampleService.
d) Building WCF client
i)
ii)
iii)
iv)
v)
address attribute.
vi) add the attribute address="http://localhost:8080/SampleService" to the endpoint tag of the
app.config file.
vii) Now add code to Program.cs so that final Program.cs should look like as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace SampleClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Ask question");
//the name AnswerClient is generated autometically by svcutil.exe
tool which creates
//chat proxy and app.cofig
//by browsing the service url after reference.
using (AnswerClient client = new AnswerClient())
{
Console.WriteLine("Your Question: ");
string question = Console.ReadLine();
string answer = client.ObtainAnswer(question);
Console.WriteLine(answer);
Console.ReadLine();
}
}
}
}
e)
M.Umamaheswara Reddy
Uma9703050520@gmail.com