CSharp

Pitfalls of C/C++
----------------------
1. Difficult for beginners to learn
2. Cannot test code until it is compiled
3. Difficult to debug without expensive debugging tools.
4. Takes longer time to develop.
5. Database  connectivity is compllicated.
6. Problems in modification of data.
7. Difficulty in implementation.-
8. Do not contain any framework.

Need for a New Language:
----------------------------------
Microsoft introduced C# as a new programming language to address the problems posed by traditional languages.

C# was developed to provide the following benefits:
-----------------------------------------------------------------
1. Create a very simple and yet powerful tool for building interoperale, scalable, robust applications.
2. Create a complete object-oriented architecture.
3. Support powerful component-oriented development.
4. Provide familiarity to programmers coming from C or C++ background.
5. Allow to write applications that target both desktop and mobile devices.

Purpose of C#:
------------------
Microsoft .Net was formely known as Next Generation Windows Services(NGWS).  It is a completely new platform for developing the next generation of Windows/Web applications.  C# is an object-oriented language derived from C and C++.

.Net Framework Fundamentals:
-----------------------------------------
The .Net Framework is a software component that can be added to the Microsoft Windows operating system.  It has a number of pre-coded solutions and it manages the execution of programs written specifically for the framework.

.Net Framework Components:-
-------------------------------------
The .net Framework has two major components.  They are:
1. CLR
2. FCL
1. The Common Language Runtime(CLR):
-----------------------------------------------------
The Common Language runtime is the backbone of .net Framewotk or It is an Execution Engine.  It performs various functions such as:

i. Memory Management
ii. Code execution
iii. Error Handling
iv. Code Safety Verification
v. Garbage Collection

2. The .Net Framework Class Library (FCL):
--------------------------------------------------------
The class library is a comprehensive object-oriented collection of reusable types.  It is used to develop applications ranging from traditional command-line to graphical user interface (GUI) applications that can be used on the web.

Organization of .NET Framework:
------------------------------------------
The .NET Framework is a multi-lingual and multi-platform environement to build, deploy and run applications.  It enables programmers to develop applcations for various platforms such as mobile devices, desktop computers, smartphones and so on.  Additionally, it support a variety of programing languages like VB.Net, VC#, VC++, VJ#, ASP.Net etc.  ASP.Net is not a language, it is a web technology to develop web application.

Architecture of .NET Framework
-------------------------------------------

________________________________________
VC++ VC# VB VJ#
________________________________________
.Net Framework Class Libraries (FCL)
________________________________________
Common Language Runtime (CLR)
________________________________________
Operating System
________________________________________

Other Components of .NET Framework:
---------------------------------------------------
CLR and FCL are major components of the .NET Framework.  Apart from these, the other important are defined below:

* Web Forms:
------------------
Provides a set of classes to design forms for the web pages similar to the HTML forms.

* Web Services:
-------------------
This includes a set of classes to design applications that can be accessed using a standard set of protocols.

Windows Forms:
---------------------
Provides a set of classes to design forms for windows-based applications.

ASP.Net:
-----------
Provides a set of classes to build web applications.
ADO.NET:
--------------
   Provides classes to interact with databases.
XML classes:
-----------------
Enables XML manipulation,searching and translations.

Base Framework Classes:
--------------------------------
These classes provide basic functionality such as input/output,string manipulation,security management,network communication and so on.

Basic Features of C#:-
-----------------------------
* Object-Oriented Programming
* Type-Safety Checking
* Garbage Collection
* Standardisation by ECMA (European Computer Manufacturers Association)
* Generic Types and Methods

* Object-Oriented Programming:-
-----------------------------------------
C# application programming focuses on objects so that code written once can be reused.  This helps reduce time and effort on the part of developers.

* Type-Safety Checking:-
--------------------------------
Uninitialized variables cannot be used in C#.  Overflow of types can be checked.  C# is a case-sensitive language.

* Garbage Collection:-
---------------------------
Performs automatic memory management from time to time and spares the programmer the task.

*Standardisation by ECMA:-
-------------------------------------
This standard specifies the syntax and constraints used to create standard C# programs.

* Generic Types and Methods:
--------------------------------------
Generics are a type of data structure that contains code that remains the same throughout but the data type of the parameters can change with each use.

Memory Management:
-----------------------------
In programming languages like C and C++, the allocation and de-allocation of memory is done manually.  Performing these tasks manually is both, time-consuming and difficult.

The C# language provides the feature of allocating and releasing memory using automatic memory management.  This means that there is no need to write code to allocate memory when objects are created or to release memory when objects are not required in the application.  Automatic memory management increases the code quality and enhances the performace and the productivity.

Garbage Collection:
-------------------------
The process of allocating and de-allocating memory using automatic memory management is done with help of a garbage collector.  Thus, garbage collection is the automatic reclaiming of memory from objects that are no longer in scope.  This means that when the object is out of scope, the memory will be freed for use so that other objects can be allotted the memory.

Data Types:
=========
You can store different types of values such as numbers, characters or strings in different variables.  but the compiler must know what kind of data a  particular variable is expected to store.  To identify the type of data that can be stored in a variable, C# provides different data types.

Data Types are divided into two categories.  Those are:

* Value Types
* Reference Types

* Value Types:
------------------
Variables of value types store actual values.  These values are stored in a stack.  The values can be either of a built-in data type or a user-defined data type.  Most of the built-in data types are value types.  The value type built-in data types are int, float, double, char and bool.  Stack storage results in faster memory allocation to variables of value types.

Reference Types:-
-----------------------
Variables of reference type store the memory address of other variables in a heap.  These values can either belong to a built-in data type or a user-defined data type.  For example, string is a built-in data type which is a reference type.  Most of the user-defined data types such as class are reference types.

Predefined Data Types:
------------------------------
The Predefined data types are referred to as basic data types in C#.  These data types have a predefined range and size. The size of the data type helps the compiler to allocate memory space and the range helps the compiler to ensure that the value is assigned is within the range of the variable's data type.

_____________________________________________________________
Data Type   Size  Range
__________________________________________________________
byte Unsigned 8-bit integer 0 to 255
short Signed 16-bit integer -32,768 to32,767
int Signed 32-bit integer
long Signed 64-bit integer
float 32-bit floating point with 7 digits precision
double 64-bit floating point with 15-16 digits precision
decimal 128-bit floating point with 28-29 digits precision
char Unicode 16-bit character
bool Stores either true or false
_____________________________________________________________
Unicode Characters:-
--------------------------
Unicode characters are represented as 16-bit characters and are used to denote multiple lnaguages spoken around the world.  The char data type uses Unicode characters and these are prefixed by the letter "U".

Signed Integers:
--------------------
Signed integers can represent both positive and negative numbers.

Float and Char Data Type Representation:
-----------------------------------------------------
A value of float type variable must always end with the letter "F" or "f".  A value of char type must always be enclosed in single quotes.

Reference Types:
---------------------
Reference Types are classified into Built-In Reference Types and User-Defined Reference Types.

i.Built-In Reference Types:
---------------------------------
Object:
---------
Object is a built-in reference data type.  It is a base class for all predefined and user-defined data types.  A class is a logical structure that represents a real world entity.  This means that the predefined and user-defined data types are created based on the object class.

String:
--------
String is a built-in reference type.  String type signifies Unicode character string values.  It allows you to assign and manipulate string values.  Once strings are created. They cannot be modified.

Class:
--------
A class is a user-defined structure that contains variables and methods.  For example, the Employee class can be a user-defined structure that can contain variables such as empsalary, empname and empaddress.  In addition, it can contain methods such as calculatesalary(), which returns the net salary of an employee.

Delegate:
------------
A delegate is a user-defined reference type that stores the reference of one or more methods.

Interface:
------------
An interface is a type of user-defined class that is used for multiple inheritance.

Array:
--------
An array is a user-defined data structure that contains values of the same data type, such as marks of students.

Rules of Variable Declaration:
-------------------------------------
* A variable name can begin with upper case or lower case letter.  The name can contain letters, digits and underscore character(_).

* The first character variable name must be a letter and not a digit.  The underscore is a legal first character, but it is not recommended at the beginning of a name.

* C# is a case sensitive language; hence  varible names count and Count refer to two different variables.

* C# keyword cannot be used as variable names.  If  you still need to use a C# keyword, prefix it with th '@' symbol.

Comment in C#:
-------------------
Singleline Comments -  //
Multiline Comments - /*      */
Xml Comments - ///

Escape Sequence Characters:
------------------------------------
An escape sequence character is a special character that is prefixed by a backslash(\).  Escape sequence characters are  used to implement special non-printing characters such as a new line, a single space or a backspace.  These non -printing characters are used while displaying formatted output to the user to maximize readbility.  The backslash character tells the compileer that the following character denotes a non-printing character.

Placeholders:
-----------------
The number in curly braces are called placeholders.  They are {0},{1} etc.

Types of Statements:
===============

Selection Statements:-
--------------------------
A selection statement is a decision-making statement that checks whether a particular condition is true or false.  The keywords associated with this statement are: if, else, switch and case.

Iteration Statements:
--------------------------
An iteration statement helps you to repeatedly execute a block of code.  The keywords associated with this statement are: do, for, foreach, in and while.

Jump Statements:-
------------------------
A jump statement helps you transfer the flow from one block to another block in the program.  The keywords associated with this statement are: break, continue, default, goto, and return.

Exception Handling Statements:
-----------------------------------------
An exception handling statement manages unexpected situations that hinder the normal execution of the program.  For example, if the code dividing a number by zero, the program will not execute properly.  To avoid this situation, you can use exception handling statements.  The keywords associated with this statement are: throw, try-catch, try-finally and try-catch-finally.

Operators Used in C#:-
-----------------------------

1.Arithematic - +,-,*,/,%
2.Logical - &&, ||, !,
3.String Concatination- +
4.Increment and Decrement - ++,--
5.Comparison  ==,!=,<,>,<=,>=
6.Assignment  =,+=,-=,*=,/=,%=
7.Member Access  .
8.Conditional  ?,:

Type Casting :
============

Need of TypeCasting:
----------------------------
Consider a payroll system of an organization.  The gross salary of  an employee calculated and stored in varibles of float type.  Currently the output is shown as float values.  The payroll department wants the salary amount as  a whole number and thus wants any digits after the decimal point of the calculated salary to be ignored.  The programmer is able to  achieve this using the typecasting feature of C#.  Typecasting allows you to change the datatype of a variable.

Definition and Benefits:
------------------------------
C# supports two types of type casting, namely Implicit and Explicit.  Typecasting mainly used to:

* Convert a datatype to another datatype that belongs to the same or different hierarchy.  For example, the numeric hierarchy includes int, float and double. You can convert the char type into int type to display the ASCII value.

* Prevent the loss of numeric data if the resultant value exceeds the range of its variable's datatype.

Implicit Typecasting:-
---------------------------
  Implicit typecasting refers to automatic conversion of datatypes.  This is done by C# compiler.  Implicit typecasting is done only when the destination and source data types belongs to same hierarchy.  In destination data type must hold a  larger range of values than the source data type.  So Implicit typecasting prevents the loss of data.  If you have int type value to, you can assign long type of variable.

int -----> Implicit Typecasting ------>long


Explicit Typecasting:-
--------------------------
Explicit typecasting refers to changing a data type of  higher precision into a data type of lower precision.  For example, using  explicit typecasting, you can manually convert the value of float type into int type.  This typecasting might result in loss of data, the digits after the decimal point are lost.

float----->Explicit Conversion----->int

Examples of Typecasting:
----------------------------------
eg1:

using System;

class MainClass
{
     public static void Main()
     {
         uint value1 = 255;
         byte value2 = (byte) value1;
        //byte value2=value1;
         Console.WriteLine("Value2: {0}", value2);
     }
}

-----------------------------------------------------------------------------------
eg2:

using System;
class MainClass
{
    public static void Main()
    {
        // all implicit
        sbyte v = 55;
        short v2 = v;
        int v3 = v2;
        long v4 = v3;
     
        // explicit to "smaller" types
    //    v3 = (int) v4;
   //     v2 = (short) v3;
     //   v = (sbyte) v2;
        Console.WriteLine("(int) is : "+v3);
        Console.WriteLine("(short) is : "+v2);
        Console.WriteLine("sbyte) is : " +v);
   
    }
}
-----------------------------------------------------------------------------
Explicit Typecasting using Built-in methods:
------------------------------------------------------------------------------
There are two ways. Those are

System.Convert class:
---------------------------
This class provides useful methods to convert any built-in data type to another.  For example, Convert.ToChar(float) method converts a float value into a char value.

ToString() method:
------------------------
This method belongs to the Object class and converts any data type value into string.

Boxing and Unboxing:
==================
Boxing:
---------
Boxing is a process for converting a value type(integers) to reference type(objects).

Example for Boxing:
----------------------------

using System;
class Test
{
static void Main()
{
char ch = 'b';
object obj = ch;
Console.WriteLine("Char value is {0}",ch);
Console.WriteLine("Object value is {0}",obj);
Console.WriteLine();
}
}

--------------------------------------------------------------------------------

Unboxing:
-------------
The process of conversion from reference type to value is known as Unboxing.

Example for Unboxing:
-------------------------------
using System;
class Test
{
static void Main()
{
// unboxing
float q = 4.6f;
object ob = q;
Console.WriteLine("Object value is {0}",ob);
float r = (float)ob;
Console.WriteLine("Float value is {0}",r);
}
}

-----------------------------------------------------------------------------



Programming Constructs:-
===================================================
1.Conditional Constructs
2.Sequence Constructs
3.Iteration Constructs

1.Conditional Constructs:-
1.Simple if Statement
2.if-else Statement
3.if else if Statement
4.Nested if Statement

1.Simple if Statement:-
Syntax:-
if(condition)
          {
            statements;
          }

2.if-else Statement:-
Syntax:-
        if(condition)
          {
            statements;
          }
        else
          {
            statements;
          }

3.if-else if statement:-
Syntax:-
        if(condition)
          {
            statements;
          }
        else if(condition)
          {
            statements;
          }
        else
          {
            statements;
          }

4.Nested if Statement:-
Syntax:-
    if(condition1)
        {
       if(condition2)
          {
    statements;
          }
       else
          {
            statements;
          }
         }
     else
        {
         if(condition3)
            {
             statements;
            }
         else
            {
             statements;
            }
           }


2.Sequence Constructs:-
  Switch-Case Statement:
Syntax:-
switch(expression)
           {
        case 1:
        statements;
break;

case 2:
statements;
break;

default:
statement;
break; //compulsory
    }


3.Iteration Constructs:-
C# provides following types of Iteration constructs.
1.The while loop
2.The do loop
3.The for loop
4.The foreach loop

1.While loop:-
The while loop executes a statement or set of statements as long as the condition specified, evaluates to true.

Syntax:-
while(condition)
            {
             //statements;
            }

2.do...whle loop:-
The do...while loop is similar to the while loop except that the body statements are executed at least once even if the condition evaluate to false.

Syntax:-
do
        {
         //statements;
        } while(condition);

3.for loop:-
The for loop allows to iterate through the loop only after a particular condition is evaluated.  It is used in situation where a statement or blocks of statements is repeated for a predetermined number of
times.

Syntax:-
for(initialization;condition;increment/decrement)
    {
    //statements;
    }

4.foreach loop:-
The foreach loop is generally used to iterate through a collection or an array.  This loop cannot be used to change the content of the collection of array.

Syntax:-

  foreach(Type Identifier in expression)
         {
   //statements
         }

eg:- foreach(char ch in str)
str - already declared variable
char - is a datatype
ch - is a variable.

Example 1:
----------------
using System;
class test
{
static void Main()
{
int a,b;
Console.WriteLine("Enter Number to a");
a=Convert.ToInt16(Console.ReadLine());

Console.WriteLine("Enter Number to b");
b=Convert.ToInt16(Console.ReadLine());

if(a>b)
     
Console.WriteLine("a is greater");
        else
Console.WriteLine("b is greater");
     
     }
  }

Example2:
----------------
using System;
class demo
{
static void Main()
{
int x,y,z;
Console.WriteLine("Enter three values");
x=Convert.ToInt16(Console.ReadLine());
y=Convert.ToInt16(Console.ReadLine());
z=Convert.ToInt16(Console.ReadLine());

   if(x>y && x>z)
Console.WriteLine("x is greater");
else if(y>z)
Console.WriteLine("y is greater");
else
Console.WriteLine("z is greater");
  }
}

Example 3:
------------------
using System;
class demo
   {
     static void Main()
       {
         string ch;
         Console.WriteLine("Enter any character : ");
 ch=Console.ReadLine();
switch(ch)
{
  case "a":
  Console.WriteLine("It is a Vowel");
  break;

  case "e":
  Console.WriteLine("It is a Vowel");
  break;

  case "i":
  Console.WriteLine("It is a Vowel");
  break;

  case "o":
  Console.WriteLine("It is a Vowel");
  break;

  case "u":
  Console.WriteLine("It is a Vowel");
  break;

  default:
  Console.WriteLine("It is a Consonant");
  break;
                }
          }
      }

Example 4:
---------------
using System;
class test
  {
   static void Main()
      {
        int i=1;
       while(i<=10)
         {
   Console.WriteLine(i);
           i=i+1;
         }
      }
   }

Example 5:
--------------
using System;
class test
   {
     static void Main()
       {
int i=10;
         do
  {

    Console.WriteLine(i);
i=i-1;
          }

       while(i>=1);
       

        }
     }
       
Example 6:
----------------

using System;
class test
  {
   static void Main()
     {
      int i;
     for(i=1;i<=10;i++)
      {
      Console.WriteLine(i);
      }
     }
   }
     
     

Example : 7
------------------

using System;
class test
  {
   static void Main()
     {
        int l=0,d=0,p=0;
        string str;
Console.WriteLine("Enter a string");
str=Console.ReadLine();

foreach(char ch in str)
{
  if(char.IsLetter(ch))
  l++;

if(char.IsDigit(ch))
  d++;

if(char.IsPunctuation(ch))
     p++;
        }

Console.WriteLine("Number of Letters: {0}",l);

Console.WriteLine("Number of Digits: {0}",d);

Console.WriteLine("Number of Punctuations: {0}",p);

    }
  }

Example 8:
----------------
using System;
class Test
{
public static void Main()
{
string[] names={"Scott","Martin","Smith"};
foreach(string str in names)
{
Console.WriteLine(str);
}
}
}
------------------------------------------------------------------------------------
Jump Statements:
------------------------
Jump statements are used to transfer control from one point in a program to another.  There will be situations where you need to exit out of a loop prematurely and continue with program.  In such cases jump statements are used.

C# supports four types of jump statements.  These are
* break
* continue
* goto
* return

break statement:
---------------------
The break statement is used in the selection and loop constructs.  It is most widely used in the swith...case construct and in the for and while loops.  The break statement is denoted by the break keyword.  In the switch...case construct, it is used to exit the loop without testing the loop condition.

Example1:
------------------------------------------------------------------------------------
using System;
class BreakDemo
{
public static void Main()
{
for(int i=1;i<=10;i+=2)
{
if(i==5)
{
//break;
 continue;
}
Console.WriteLine(i);


}


}
}
----------------------------------------------------------------------------------

continue statement:
-------------------------
The continue statement mostly used in loop constructs.  The statement is denoted by continue keyword.  The continue statement is used to end the current iteration of the loop and transfer the program control back to the beginning of the loop.  The statements of  the loop following the continue statement are ignored in the current iteration.

The "goto" Statement:
----------------------------
The goto statement allows you to directly execute a labeled statement or a labeled block of statements.  A labeled block or labeled statement starts with a label.  A label is an identifier ending with a colon.  A single  labeled block can be referred by more than one goto statements.

Example on goto statement:
-----------------------------------
using System;
class Test
{
public static void Main()
{
 int i=0;
display :Console.WriteLine("Hello World..");
i++;
if(i < 5)
{
goto display;
}

}
}
----------------------------------------------------------------------------
The "return" Statement:
--------------------------------
The return statement is used to return a value of expression  The return statement is denoted by the return keyword.  The return statement must be the last statement in the method block.
      
     
===============================================
Purpose of Array:
----------------------
Consider a program that stores the names of 100 students. To store the names, the programmer would create 100 varibles of type string.  In such situations, the programmer can create an array for storing the 100 names in single variable.

Difinition of an Array:
----------------------------
 Arrays are group of values of same datatype.  These values are stored in adjacent memory locations, making it easier to access and manipulate them.  Each value is referred to as an element.  These elements are accessed using index numbers that determine the position of the eleement in the array list.

C# supports zero-based index values in an array.  This means that the first array element has index number zero while the last elements has index number n-1, where n stands for the total number of elements in the array.

Declaring an Array:-
-------------------------
datatype arrayname=new datatype[size of an array];

datatype - any valid datatype in C#
number of elements - the size of the array
variable name - name of the array.

eg:-
1.string[] array2=new string[5];

2.int[] arr=new int[5];


3.string[] array3={"right","left","top","down"};

4.int[] array4={10,20,30,40,50};

Example on Array:
------------------------
// Accepting five values and printing them.

using System;
class test
{
static void Main()
{
  int[] arr=new int[5];
  Console.WriteLine("Enter 5 numbers in array:");
for(int i=0;i<5;i++)
  {
   arr[i]=Convert.ToInt16(Console.ReadLine());
          }
Console.WriteLine("Printing Array");

for(int i=0;i<5;i++)
{
Console.WriteLine(arr[i]);
}
      }
    }


Types of Arrays:
---------------------
1. Single Dimensional Array
2. Multi Dimensional Array

1. Single Dimensional Array:-
------------------------------------
The elements of a single-dimensional array are stored in a single row in the allocated memory.

Example of SingleDimensional Array:
---------------------------------------------------
using System;
class SingleDimensionalArray
{
public static void Main()
{
string[] students={"Scott","Martin","Smith"};

for(int i=0;i<students.Length; i++)
{
Console.WriteLine(students[i]);
}
}
}

---------------------------------------------------------------------------
Multi-Dimensional Array:-
---------------------------------
Consider a scenario where we need to store the roll numbers of 50 students and their marks in three exams.
Using a single-dimensional array, we require two separate arrays for storing rollnumbers and marks.  However, using a multi-dimensional array, we just need one array to store both, roll numbers as well as marks.

A multi-dimensional array allows you to store combination of values of a single type in two or more dimensions.  The dimensions of the array are represented as rows and columns similar to the rows and columns of a Microsoft Excel Sheet.

There are two types of multi-dimenstional arrays.  Those are  1. Rectangular Arrays and 2. Jagged Arrays.

 1. Rectangular Arrays:
------------------------------
A rectangular array is multi-dimensional array where all the specified dimensions have constant values.  A ractangular array will always have the same number of columns for  each row.

Example on Rectangular Array:
-----------------------------------------

using System;
class RectangularArrayDemo
{
public static void Main()
{
int[,] dimension=new int[4,5];
int numone=0;
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
dimension[row,col]=numone;
numone ++;

}
}
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++)
{
Console.Write(dimension[row,col]+"\t");
}
Console.WriteLine();
}
}
}

-------------------------------------------------------------------------
Jagged Array:
------------------
A jagged array is a multidimensional array where one of the specified dimensions can have varying sizes.  Jagged arrays can have unequal number of columns for each row.

Example of Jagged Array:
---------------------------------

using System;
class JaggedArrayDemo
{
public static void Main()
{
string[][] companies=new string[3][];
companies[0]=new string[]{"Intel","AMD"};
companies[1]=new string[]{"IBM","Microsoft","Sun"};
companies[2]=new string[]{"HP","Canon","Lexmark","Epson"};
for(int row=0;row<companies.Length;row++)
{
Console.Write("List of companies in group "+(row+1) + ":\t");
for(int col=0;col<companies[row].Length;col++)
{
Console.Write(companies[row][col] + " ");
}
Console.WriteLine();
}
}
}

--------------------------------------------------------------------------
The Array Class:
-----------------------
Consider a code that stores the marks of a particular subject for 100 students.  The programmer wants to sort the marks, and to do this, he has to manually write the code to perform sorting.  If the array is declared as an object of the Array class, the built-in methods of the Array class can be used to sort the array.

The Array class is a built-in clas in the System namespace and is the base class for all arrays in C#.  The Array class provides methods for various tasks such as searching, copying and sorting arrays.

Examples on Arrays:
================
Printing Student Names
-------------------------------------
using System;
class test
   {
     static void Main()
{
  int count;
  Console.WriteLine("Enter the no.of students you wish to register");
  count=Convert.ToInt16(Console.ReadLine());

string[] names=new string[count];


for(int i=0; i<count; i++)
   {
Console.WriteLine("Enter the name of Student {0}",i+1);
names[i]=Console.ReadLine();
   }
Console.WriteLine("The Students who have registered are as follows:");

foreach(string disp in names)
    {
      Console.WriteLine("{0}",disp);
    }
   }
 }
------------------------------------------------------------------------
Copying Array Values from one another:-
---------------------------------------------------------------------
using System;
class test
    {
      public static void Main()
{
int[] a={40,50,10,30,20};
int[] b=new int[5];
int i;
for(i=0;i<5;i++)
Console.WriteLine(a[i]);

//Copying the  Array Values from one to another

Array.Copy(a,b,5);
Console.WriteLine(" After Copying: ");
for(i=0;i<5;i++)
Console.WriteLine(b[i]);
                 }
    }

-------------------------------------------------------------------
Sorting of an Array:-
------------------------------------------
using System;
class test
    {
       static void Main()
{
int[] a={40,50,10,30,20};
int i;
for(i=0;i<5;i++)
Console.WriteLine(a[i]);

//Sorting An Array

Array.Sort(a);
Console.WriteLine(" After Sorting: ");
for(i=0;i<5;i++)
     Console.WriteLine(a[i]);

                 }
    }

-----------------------------------------------------------------------
Length of an Array
--------------------------------------------
using System;
class test
    {
       public static void Main()
{
int[] a={40,50,20,30,10,34,45,66,78,88};
int i;
for(i=0;i<10;i++)
Console.WriteLine(a[i]);

// Length Property

Console.WriteLine("Length of Array is :{0}",a.Length);
                  }
     }
------------------------------------------------------------------
Array Reverse:-
----------------------------------------------
using System;
class test
    {
      public static void Main()
{
int[] a={40,50,10,30,20};
int i;
for(i=0;i<5;i++)
Console.WriteLine(a[i]);

// Reverse the Values in an Array

Array.Reverse(a);
Console.WriteLine("\n After Reversing ");
for(i=0;i<5;i++)
Console.WriteLine(a[i]);
                 }
     }
-------------------------------------------------------------
Sum of an Array:
------------------------------------------------
//Accepting the values and sum

using System;
class demo
{
static void Main()
{
int[] arr=new int[5];
int sum=0;
Console.WriteLine("Enter five numbers in an array: ");
for(int i=0;i<5;i++)
{
arr[i]=Convert.ToInt16(Console.ReadLine());
}
for(int i=0;i<5;i++)
{
sum=sum+arr[i];
}
Console.WriteLine("The Sum {0} ",sum);
}

  }
--------------------------------------------------------------
Get the value for given Index:
--------------------------------------------------

using System;
class test
    {
       public static void Main()
{
int[] a={40,50,20,30,10};
int i;
for(i=0;i<5;i++)
Console.WriteLine(a[i]);

// GetValue Property

Console.WriteLine("Enter the Index");
int ind=Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Content of Index {0} is {1} ",ind,a.GetValue(ind));
                   }
       }
=================================================
OBJECT ORIENTED PROGRAMMING SYSTEM
=================================================

OOPS:- Object Oriented Programming Language
---------------------------------------------------------------
It is very important  concept in C#  Language.  OOPS have three parts based on their process.

a.OOD:-Object Oriented Designing
b.OOA:-Object Oriented Approach
c.OOP:-Object Oriented Programming
The combination of above three parts are called "OOPS".

Above all process is used to develop any application systematically by following set of predefined standards.  All the standards comes under "Unified Modiling Language"(UML)

a.Object Oriented Designing(OOD):-
---------------------------------------------
It stands for object oriented design.  It determines to develop the application by phasewise designing of each module and each module will be designed later by following set of methods, principles and applications.

b.Object Oriented Approach(OOA):-
----------------------------------------------
It follows the object oriented designing based on its (OOD) phase.

c.Object Oriented Programming(OOP):-
--------------------------------------------------
It determines the real implementation of program(coding) by following set of functions libraries,header files and other technical tools by performing a suitable syntaxes.  Any real implementation of the program in OOP which follows a standard structure of program.

In C# we have a standard structure of program.  If you write program we should clear about object.

* Standard Structure of Program in OOPS:-

class
Object
objective
  1.Data Members
2.Member Functions



Class:-
In a C# program the "class"  keyword denotes that the C# program follows this standard of class structure.
(or)
Class is nothing but collection of data and functions.
(or)
Collection of data members and member functions.



2.Objective:-
It is a invisible and it is the end result of an application which can be achieved using data members and member functions. Objective means end result of the programme.

3.Data Members:-
Data members are the elements which can be participated in a prog to achieve the objective of an application.

4.Member Function:-
It is a process of a technic in a program which can take a parameter and returns a value.  Member function can be called methods in OOPS Programming.

5.Object:-
It is a instance of a class which can be gives the reference to its.  The data member and the member functions which can be used outside of the class.
(or)
Object is nothing but instance of class.

Datatypes:-
Datatypes which are denotes what type of data that your processing to our program.

Variables:-
It is a location memory where we can store the values into the memory those values in the memory called "constants".

   OOPS:- Object Oriented Programming System
--------------------------------------------------------------
1.Encapsulation
2.Data Abstraction
3.Polymorphism
4.Inheritance

1.Data Encapsulation:-
The union of data and functions into objects is known as Data Encapsulation.
(or)

Details of what a class contains need not be visible to other classes and objects that use it.  Instead, only specific information can be made visible and the others can be hidden.  This is achieved through encapsulation, also called data hiding.  Both abstraction and encapsulation are complementary to each other.

Data Abstraction:-
-----------------------
We can give restricting the data, to set a number of functions.
(or)
It gives security.
(or)

Abstraction is the feature of extracting only the required information from objects.  For example, consider a television as an object.  It has a manual stating how to use the television.  However, this manual does not show all the technical details of television, thus giving only an abstraction to the user.

Polymorphism:-
-------------------
It is ability to take more than one form.
(or)
Use of something for different purposes.
(or)

Polymorphism is the ability to behave differently in different situations.  It is basically seen in programs where you have multiple method declared with the same name but with diferent parameters and different behavior.

Inheritance:-
----------------
Relation between two classes.
(or)
Object of one class can acquire the properties of  another class.
(or)

Inheritance is the process of creating a new class based on the attributes and methods of an existing class.  The existing class is called the base class whereas the new calss created is called the derived class.  This is very important concept of objet-oriented programming as it helps to reuse the inherited attributes and methods.

Base Class:-
---------------
It is a old class or parent class
Derived Class:-
--------------------
It is a new class or child class which can acquire the properties from base class.


Public:-
............
The data, which has been declared as public that particular data through  the program we can access.

Private:-
..............
The data, which has been declared as a private, the data can be accessed within the class only.

Protected:-
...................
The data, which has been declared as a protected, that data can be accessed within the derived classes.

internal:-
..............
The internal access modifier allows the class members to be accessible only within the classes of the same assembly.  An assembly in a file that is automatically generated by the compiler upon successful compilation of a .NET application.

--------------------------------------------------------------------------------
Example on class and object:
------------------------------------------------------------------------------
using System;
public class demo
  {
public void display()
{
Console.WriteLine("This is member function of class");
                  }
public void display1()
{
      Console.WriteLine("This is Second function of class");
                  }

    }
class test
  {
static void Main()
{
demo d=new demo();
d.display();
d.display1();
                 }
     }
-------------------------------------------------------------------------

------------------------------------------------------------------------------
Static Methods:
---------------------
    A method, by default, is called using an object of the class.  Static methods cannot be instantiated means if any method  declared with static keyword, without creating object for the class we can call.  For example, the Main() method is a static method and it does not require any instance of the class for it to be invoked.  A static method can directly refer only to static variables and other static methods of the class.

Example for Static Method:
----------------------------------------------
using System;
class Test
{
public static void Addition(int x,int y)
{
Console.WriteLine(x+y);
}
public void Multiply(int x,int y)
{
Console.WriteLine(x * y);
}
}
class Demo
{
static void Main()
{
Test.Addition(10,20);
Test t=new Test();
t.Multiply(10,20);
}
}
------------------------------------------------------------------------------
Static Variables:
----------------------
A static variable is a special variable that is accessed without using an object of a class.  A variable is declared as static using the static keyword.  When a static variable is created, it is automatically initialized before it is accessed.  An instance of a class cannot access static variables.

Example of Static Variable:
------------------------------------------
using System;
class Test
{
 static int eno=101;
 static string ename="Uma";
static void Main()
{
Console.WriteLine("Employee ID is "+eno);
Console.WriteLine("Employee Name is " + ename);
}
}
--------------------------------------------------------------------------
Constructor:-
----------------------------------------------
Constructors are special member function whose name is same as a class name constructors are need not require to be called because it is invoked automatically in the objects are created.  Constructor may have an argument or may not have an argument.  Constructors have no return type.

Normal Method:-
---------------------
A normal method may have any name associated with it. Normal methods may or may not return values.  Normal methods may be invoked any time anywhere once an object is created.

Example on Constructor:
-----------------------------------
using System;
public class demo
{
public demo()
{
        Console.WriteLine("This is a parameterless constructor");
}
}
class Test
{
static void Main()
{
demo d=new demo();
}
}
-------------------------------------------------------------------------
Method Overloading:
--------------------------
No class is allowed to contain two methods with the same name and same signature.  However, it is possible for a class to have two methods having the same name but different signatures.  The concept of declaring more than one method with the same method name but different signatures is called method overloading.

Constructor Overloading:
-------------------------------
The concept of declaring more than one constructor in a class is called constructor overloading.  The process of overloading constructor is similar to overloading methods.  Every constructor has a signature similar to that of a method.  You can declare multiple constructors in a class wherein each constructor will have different signatures.  Constructors reduce the task of assigining different values to member variables each time when needed by different objects of the class.

Example of Constructor Overloading:
---------------------------------------------------
using System;
public class demo
{
public demo()
{
        Console.WriteLine("This is a parameterless constructor");
}
public demo(int x)
 {
   Console.WriteLine("The Value of x is: {0}",x);
           }     
public demo(string str)
{
                  Console.WriteLine("The Value of string is: {0}",str);
}
public demo(double f)
{
                  Console.WriteLine("The Value of Float is: {0}",f);
}
 }
class test
{
static void Main()
{

double a;
Console.WriteLine("Enter a value");
a=Convert.ToDouble(Console.ReadLine());
demo d=new demo();
demo d1=new demo(12);
demo d2=new demo("Aptech Computer Education");
demo d3=new demo(a);
         }
}
-------------------------------------------------------------------------
Static Constructor:
----------------------------------------------------
A static constructor is used to initialize static variables of the class and to perform a particular action only once.  It is invoked before any static member of the class is accessed.

A static constructor does not take any parameters and does not use any access modifiers because it is invoked directly by the CLR instead of the object.  In addition, it cannot access any non-static data member of the class.

Example of Static Constructor:
-----------------------------------------
using System;
class Multiplication
{
static int x=10;
static int y;

static Multiplication()
{
Console.WriteLine("Static Constructor initialized");
y=x*x;
}
public static void Method()
{
Console.WriteLine("Value of Product=  " + y);
}
static void Main()
{
Multiplication.Method();
}
}

-------------------------------------------------------------------------
Destructors:-
------------------------------------------
A destructor is a special method which has the same name as the class but starts with character "~" before the class name.  Destructors immediately de-allocate memory of objects that are no longer required.  They are invoked automatically when the objects are not in use.  We can define only one destructor in a class.  Destructors have some more features:

* Destructors cannot be oveloaded or inherited.
* Destructors cannot be explicitly invoked.
* Destructors cannot specify acces modifiers and cannot take parameters.

Example on Destructor:
-------------------------------------------

using System;
class demo
{
public demo()
{
Console.WriteLine("This is parameterless constructor");
}
public demo(int x)
{
Console.WriteLine("The Value of x is: {0}",x);
}
public demo(string str)
{
  Console.WriteLine("The Value of str is: {0}",str);
 }
public demo(float x)
{
Console.WriteLine("The value of x is: {0}", x);
                    }

~demo()   // is a destructor
{
Console.WriteLine("This is a destructor");
}
    }
class test
{
static void Main()
{
demo d=new demo();
demo d1=new demo(100);
demo d2=new demo("Aptech");
demo d3=new demo(42424);
  }
  }
----------------------------------------------------------------------------
/* this keyword:
--------------------------------------------------------
The this keyword is used to refer to the current object of the class.  It is used to resolve conflicts between variables having same names and to pass the current object as a parameter.  You cannot use the this keyword with static variables and methods. */

using System;
class Dimension
{
double length,breadth;
public double area(double length,double breadth)
{
this.length=length;
this.breadth=breadth;
return length * breadth;
}
static void Main()
{
Dimension d=new Dimension();
Console.WriteLine("Area of rectangle= " + d.area(10.5,12.5));
}
}

---------------------------------------------------------------------
Inheritance:
==========
The mechanism of deriving a new class with the help of old class is known as inheritance.  Old class is known as base class and new class is known as a derived class.

Example on Inheritance:
-----------------------------------
using System;
public class democlass
{
public void display()
{
Console.WriteLine("This is the base class's function");
                    }
                 }
public class derived:democlass
{
public void display1()
{
Console.WriteLine("This is the derived class's function");
                  }
}
class test
{
static void Main()
{
derived d=new derived();
d.display();
d.display1();
                  }
}

--------------------------------------------------------------------------
Example of Inheritace with Constructor:
----------------------------------------------------
// Inheritance Using Constructor

using System;
 public class demo
{
public demo()
     {
Console.WriteLine("This is base class's constructor");
                      }
                }
public class derived:demo
{
public derived()
     {
Console.WriteLine("This is derived class's constructor");
                      }
public void deriv()
{
Console.WriteLine("This is second method in derived class");
                 }

                  }

class test
        {
static void Main()
{
derived d=new derived();
d.deriv();

 
}
        }


--------------------------------------------------------------------------
Example on Multi-level Inheritance:
------------------------------------------------
using System;
public class Epack
{
public void C()
{
Console.WriteLine("C is a middle level language");
}
}
public class ITBooster:Epack
{
public void DotNet()
{
Console.WriteLine(".Net is a framework");
}
}
public class ACCP:ITBooster
{
public void Java()
{
Console.WriteLine("Java is a platform independent");
}
}
public class Aptech
{
static void Main()
{
ACCP A=new ACCP();
A.C();
A.DotNet();
A.Java();
}
}

--------------------------------------------------------------------------
Example on Multi-level Inheritance with Constructor
-----------------------------------------------------------------
using System;
public class Polygon
{
public Polygon()
{
Console.WriteLine("This is Polygon method");
}
}
public class Circle:Polygon
{
public Circle()
{
Console.WriteLine("This is Circle Method");
}
}
public class Rectangle:Circle
{
public Rectangle()
{
Console.WriteLine("This is Rectangle");
}
}
public class Aptech
{
static void Main()
{
Rectangle R=new Rectangle();
}
}
-------------------------------------------------------------------------------
"protected" Access Modifier:-
--------------------------------------
The protected access modifier protects the data members that are declared using this modifier.  The protected modifier is specified using the protected keyword.  Variables or methods that are declared as protected are accessed only by the class in which they are declared or by a class that is derived from this class.

Example of "protected" Access Modifier:
---------------------------------------------------
using System;
class Animal
{
 protected int sno;
protected string sname;
}
class Cat : Animal
{
static void Main()
{
Cat C=new Cat();
C.sno=101;
C.sname="Scott";
Console.WriteLine("The Student No is  " + C.sno+ ".");
Console.WriteLine("The Student Name is  " +C.sname+".");
}
}
--------------------------------------------------------------------------------
Polymorphism:-
===================================
/*
Polymorphism is derived from two Greek words, namely Poly and Morphos.  Poly means many and Morphos means forms.  Polymorphism means existing in multiple forms.  Polymorphism is the ability of an entity to behave differently in different situations.  The two methods in class having the same name but different signatures performing the same basic operation but in different ways.

To assign two integer values,string values and double values and add  them. */

using System;
public class demo
{
public int sum(int x,int y)
                   {
return x+y;
                   }
                   public string sum(string x,string y)
           {
                  return x+y;
                   }
                   public double sum(double x,double y)
                   {
                 return x+y;
                   }
public int sum(int x,int y,int z)
                   {
                 return x+y+z;
                   }
}
class test
{
static void Main()
                   {
                demo d=new demo();
Console.WriteLine("The Sum of integer value is :{0}",d.sum(10,20));
Console.WriteLine("The String value is :{0}",d.sum("Aptech Computer Education "," Dwarakanagar"));

Console.WriteLine("The Sum of double value is :{0}",d.sum(10.23,20.54));
Console.WriteLine("The Sum of multiple integer value is :{0}",d.sum(10,20,30));
              }
}
--------------------------------------------------------------------------

Method Overriding:
===============
Method overriding is a feature that allows the derived class to override or redefine the methods of the base class.  Overriding a method in the derived class can change the body of the method that was declared in the base class.  Thus, the same method with the same name and signature declared in the base class can be reused in the derived class to define a new behavior.

The method implemented in the derived class from the base class is known as the Overriden Base Method. Using Overriding concept in method can be overrided.  While defining a method in derived class the keyword 'new' should be used.

Example of MethodOverriding:-
-------------------------------------------------------------------------
/* Overriding:-
        Using Overriding concept in method can be overrided.  While defining a method in derived class the keyword 'New' should be used.  */

using System;
public class baseclass
{
public void display()   // function
{
Console.WriteLine("This is normal function is base class ");
                  }
}
public class derived:baseclass
{
public new void display()
                  {
Console.WriteLine("This is override function is derived class");
                   }
}

class test
{
static void Main()
{
derived d=new derived();
d.display();
                  }
 }

--------------------------------------------------------------------------------
Compile-time and Run-time Polymorphism:
------------------------------------------------------
Polymorphism can be broadly classified into two categories,
compile-time polymorphism and run-time polymorphism.

Compile-time Polymorphism:-
--------------------------------------
* It is implemented through method overloading.
* It is executed at the compile-time since the compiler knows which method to execute depending on the number of parameters and their data types.
* It is referred to as static polymorphism.

Run-time Polymorphism:
-------------------------------
* It is implemented through method overriding.
* It is executed at run-time since the compiler does not know the method to be executed, whether it is the base class method that will be called or the derived class method.
* It is referred to as dynamic polymorphism.
---------------------------------------------------------------------------
/* Virtual Method in Polymorphism:-

--------------------------------------------------
This method is used when a same functiion name is used in base class as well as derived class which contains different tasks.  The 'virtual' keyword should be used only in a baseclass while declaring the function.  But 'override' keyword should be used in derived class.    */

using System;
public class baseclass
{
public virtual void display()
{
Console.WriteLine("This is Virtual Function");
}
}
public class derived:baseclass
{
public override void display()
{
Console.WriteLine("This is override function of derived class");
}
}
public class derived2:baseclass
{
public override void display()
{
Console.WriteLine("This is override function derived2 class");
}
}
class test
{
static void Main()
{
baseclass dc=new baseclass();
derived d=new derived();
derived2 d2=new derived2();

dc.display();
d.display();
d2.display();
      }
}
 
------------------------------------------------------------------------------
Purpose of Sealed Classes:
----------------------------------------------------
Consider a class named SystemInformation that consists of critical methods that affect the working of the operating system.  You might not want any third party to inherit the class SystemInformation and override its methods, thus causing security and copyrigt issues.  Here, you can declare the SystemInformation class as sealed to prevent any change in its variables and mehods.

A Sealed class is a class that prevents inheritance.  You can declare a sealed class by preceding the class keyword with the sealed keyword.  The sealed keyword prevents a class from being inherited by any other class.  Therefore, the sealed class cannot be a base class as it cannot be inherited by any other class.
If a class tries to derive a sealed class, the C# compiler generates an error.

----------------------------------------------------------
Example of Sealed Class
----------------------------------------------------------
using System;
class test
{
public virtual void print()
{
Console.WriteLine("Hai");
}
}
class derived:test
{
public override  sealed void print()
{
Console.WriteLine("This information should not be overiden");
}
}
class sealedtest:derived
{
public override void print()
{
Console.WriteLine("This statement won't get executed");
}
static void Main()
{
test t=new test();
t.print();
}
}
------------------------------------------------------------------------------
Abstract Class:
----------------------------
A class that is defined using the abstract keyword and that contains at least one method which is not implemented in the class itself is referred to as abstract class.  Means the abstract class contains at least one method without a body, the class cannot be instantiated using the new keyword.  While declaring an abstract class or abstract method the keyword 'abstract' should be used.  The abstract base class, but it should be defined in derived class by using the keyword 'override'. It is not mandatory for the abstract class to contain only abstract methods.  An abstract class cannot be sealed.

Example of Abstract Class:
---------------------------------------------
using System;
public abstract class democlass
{
public abstract void display();  //abstract method

public void example() //normal method
  {
Console.WriteLine("This is the normal function of base class");
                  }
}
public class derived:democlass
{
public override void display()
     {
Console.WriteLine("This is the implementing of abstract method");
                  }
}

 class test
{
 static void Main()
            {
derived d=new derived();
d.display();
d.example();
// democlass dc=d;        
 //dc.display();
 //dc.example();
            }
}

-------------------------------------------------------------------------------
Interfaces:-
================
An interface contains only abstract members.  Unlike an abstract class, an interface cannot implement any method.  But similar to an abstract class, an interface cannot be instantiated.  An interface can only be inherited by classes or other interfaces.  An interface is declared using the keyword interface.  In C# by default, all members declared in an interface have public as the access modifier.  Interfaces does not allow the normal methods.

Example of Interfaces:
-----------------------------------
using System;
public interface myinter
{
int sum(int x,int y);
int sub(int x,int y);
}
public class demo:myinter     // inheriting the interface
{
public int sum(int x,int y)
{
return x+y;
}
                  public int sub(int x,int y)
{
return x-y;
}
}
class test
{
static void Main()
{
demo d=new demo();
int x,y;
Console.WriteLine("Enter two numbers:");
x=Convert.ToInt16(Console.ReadLine());
y=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The Sum of {0} & {1} is {2}",x,y,d.sum(x,y));
Console.WriteLine("The Subtraction of {0} & {1} is : {2}",x,y,d.sub(x,y));
                }
}      
 
-------------------------------------------------------------------------------

Multiple Interfaces:-
--------------------------------------
In CSharp, there is no concept of multiple inheritance, but here morethan one interface can be used.

Example of Multiple Interface:
--------------------------------------------------
using System;
public interface myinter
{
int sum(int x,int y);
                  int sub(int x,int y);
}
public interface myinter2
{
int mul(int x,int y);
                   int div(int x,int y);
}
public class demo:myinter,myinter2
{
public int sum(int x,int y)
                   {
               return x+y;
                  }
                 public int sub(int x,int y)
                 {
                  return x-y;
                 }
                 public int mul(int x,int y)
                 {
                  return x*y;
                 }
                 public int div(int x,int y)
                 {
                  return x/y;
                 }
}
class test
{
 static void Main()
                   {
                   demo d=new demo();
                    int a,b;
Console.WriteLine("Enter two numbers : ");
a=Convert.ToInt16(Console.ReadLine());
b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The Sum of {0} & {1} is : {2} ",a,b,d.sum(a,b));
Console.WriteLine("The Subtraction of {0} & {1} is : {2} ",a,b,d.sub(a,b));
Console.WriteLine("The Multiplication of {0} & {1} is : {2} ",a,b,d.mul(a,b));
Console.WriteLine("The Division of {0} & {1} is : {2} ",a,b,d.div(a,b));
}
}

------------------------------------------------------------------------------
// Working With Class and Interface
-------------------------------------------------------

using System;
public interface myinter
{
int sum(int x,int y);
                  int sub(int x,int y);
     
}
public class demo
{
public void display()
                  {
               Console.WriteLine("This is the normal function of base class");
       }
}
public class derived:demo,myinter
{
public int sum(int x,int y)
                  {
                   return x+y;
               }      
public int sub(int x,int y)
                  {
                    return x-y;
                  }
public void display1()
{
Console.WriteLine("This method belongs to Derived Class");
}


           }
class test
{
static void Main()
                  {
                    derived d=new derived();
                   d.display();
                  d.display1();
                int a,b;
Console.WriteLine("Enter two numbers: ");
a=Convert.ToInt16(Console.ReadLine());
b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The Sum of {0} & {1} is :{2}",a,b,d.sum(a,b));
Console.WriteLine("The Subtraction of {0} & {1} is :{2}",a,b,d.sub(a,b));
            }
     }
--------------------------------------------------------------------------------
Differences between Abstract Classes and Interfaces:
--------------------------------------------------------------------------------
Abstract Classes:
------------------------------
* An abstract class can inherit a class and multiple interfaces.
* An abstract class can have methods with a body.
* An abstract class method is implemented using the override keyword.
* An abstract class is a better option when you need to implement common methods and declare common abstract methods.
* An abstract class can declare constructors and destructors.

Interfaces:-
----------------
* An interface can inherit multiple interfaces but cannot inherit a class.
* An interface cannot have methods with a body.
* An interface method is implemented without using the override keyword.
* An interface is a better option when you need to declare only abstract methods.
* An interface cannot declare constructors or destructors.
================================================

Properties:
---------------
Access modifiers like public, private, protected and internal are used to control the accessibility of fields and methods in C#.  The public fields are accessible by other classes but private fields are accessible only by the class in which they are declared.  C# uses a feature called properties that allows you to set and retrieve values of fields declared with any access modifier in a secured manner.  This is because properties allow you to validate values before assigning them to fields.

Properties allow you to protect a field in the class by reading and writing to the field through a property declaration.  A properties can be a name of a employee or may a number of employee.

Properties are three types.

1.Read Only Property
2.Write Only Property
3.Read and Write Property

1.Read Only Property:-
------------------------------
The read-only property allows you to retrieve the value of a private field.  To create a read-only property, you should define the get accessor.

It is mandatory to always end the get accessor with a return statement.

2.Write Only Property:
-----------------------------
The write-only property allows you to change the value of a private field.  To create a write-only property, you should define the set accessor.

value keyword is mandatory.

3.Read and Write Property:
-----------------------------------
The read-write property allows you to set and retrieve the value of a private field.  To create a read-write property,  you should define the set and get accessors.

Example of Read and Write Property:
-------------------------------------------------
using System;

class employee
{
 string emp_name;
 int emp_id;
 float sal;

public string empname
{
get
{
return emp_name;
}
set
{
emp_name=value;
}
}
public int empid
{
get
{
return emp_id;
}
set
{
emp_id=value;
}

}
public float salary
{
get
{
return sal;
}
set
{
if(value < 0)
{
sal=0;

}

else
{
sal=value;
}

}
}
}

class salarydetails:employee
{
static void Main()
{
salarydetails s=new salarydetails();
s.empname="Ravi";
s.empid=101;
s.salary=-8000.50f;
Console.WriteLine("Name : {0}",  s.empname);
Console.WriteLine("No : {0}", s.empid);
Console.WriteLine("Salary : {0} ", s.salary);
}
}

--------------------------------------------------------------------------------
Example of Read-Only Property:
---------------------------------------------
//Read Only Property
using System;
class books
{
string book_name;
int book_id;

public books(string name, int value)
{
book_name=name;
book_id=value;
}
public string bookname
{
get
{
return book_name;
}
}

public int bookid
{
get
{
return book_id;
}
}
}

class test
{
static void Main()
{
books d=new books(".Net Book",1101);
Console.WriteLine("Book Name {0} ",d.bookname);
Console.WriteLine("Book Name {0} ",d.bookid);
}
}

--------------------------------------------------------------------------------
Example of Write-Only Property:
--------------------------------------------------
//Write Only Property

using System;
class department
{
string dept_name;
int dept_id;
public string deptname
{
set
                       {
dept_name=value;
     }
                    }
public int deptid
{
  set
                        {
  dept_id=value;
      }
 }

public void display()
{
Console.WriteLine("Department Name : {0}",dept_name);
Console.WriteLine("Department ID :{0} ",dept_id);
}
}
class company
{
static void Main()
{
department d=new department();
d.deptid=101;
d.deptname="Infosys";
d.display();
}
}
---------------------------------------------------------------------------------
Static Properties:
--------------------------
A property can be declared as static by using the static keyword.  A static property is accessed using the class name. The set and get accessors of the static property can access only the static members of the class.

Example of Static Property:
------------------------------------------
//Static Property
using System;
class university
{
 public static string dept_name;
 public static string university_name;

public static string department
{
   get
         {
return dept_name;
                            }
                       set
                             {
                                     dept_name=value;
           }
                      }
             
                      public static string universityname
     {
         get
                                {
return university_name;
                                 }
                            set
                                  {
 university_name=value;
                }
                          }
}
class physics
{
static void Main()
{
university.universityname="A.U.";
university.department="Physics";
Console.WriteLine("Uneversity Name: {0} ", university.universityname);
Console.WriteLine("Department Name: {0} ", university.department);

}
}
=================================================
Differences between Properties and Fields:
--------------------------------------------------------
Properties:
---------------
* Properties are data members that can assign and retrieve values.
*Properties are defined as a series of executable statements.
* Properties are defined with two accessors or methods, the get and set accessors.
* Properties can perform custom actions on change of the field's value.
* Creating a property with the name of Amount
public int Amount
{
get{};
set{};
}

Fields:
------------
* Fields are data members that store values.
* Fields are variables that can be defined in  a single statement.
* Fields are not defined with accessors.
* Fields are not capable of performing any customized actions.
* Creating field with the name is Amount
private int Amount;
================================================
Indexers:
================
Purpose of Indexers:-
--------------------------
Consider a high school teacher who wants to go through  the records of a particular student to check the student's progress.  If the teacher calls the appropriate methods every time to set and get a particular record, the task becomes a little tedious.  On the other hand, if the teacher creates an indexer for Student ID, it makes the task of accessing the record much easier.  This is because indexers use index position of the Student ID to locate the student record.

Indexers:-
-------------
Indexers are data members that allow you to access data within objects in a way that is similar to accessing arrays.  Indexers provide faster access to the data within an object as they help in indexing the data.  In arrays, you use the index position of an object to access its value.  Similarly an indexer allows you to use the index of an object to access the values within the object.

The implementation of indexers are similar to properties, except that the declaration of an indexer can contain parameters.  In C#, indexers are also known as smart arrays.

Declaration:
-----------------
* An access modifier, which decides the scope of the indexer.
* The return type of indexer, which specifies the type of value an indexer will return.
* The this keyword, which referes to the current instance of the current class.
* The bracket notation ([]), which consists of the data type and the identifier of the index.
* The Open and close curly braces, which contain the declaration of the set and get accessors.

Example of Indexers:
------------------------------------
using System;
class IndexerDemo
{
public string[] empname=new string[2];
public string this[int x]
{
get
{
    return empname[x];
}
set
{
    empname[x]=value;
}
}
static void Main()
{
IndexerDemo d=new IndexerDemo();
d[0]="Scott";
d[1]="Smith";
Console.WriteLine("Employee Names ");
Console.WriteLine(d[0]+"  and  "+d[1]);
}


-------------------------------------------------------------------------------
Differences between Properties and Indexers:
-----------------------------------------------------------
Properties:
---------------
* Properties are assined a unique name in their declaration.
* Properties are invoked using the specified name.
* Properties can be declared as static.
* Properties are always declared without parameters.
* Properies cannot be overloaded.

Indexers:-
----------------
* Indexers cannot be assigned a name and use the this keyword in their declaration.
* Indexers are invoked through an index of the created instance.
* Indexers can never be declared as static.
* Indexers are declared with at least one parameter.
* Indexers can be overloaded.
=================================================
Namespaces:
===================
System-defined Namespaces:
-------------------------------------
The .NET Framework consists of built-in namespaces that contain built-in classes, interfaces, delegates etc.  These namespaces are referred to as system-defined namespace. The main namespace or root namespace is "System".

System.Collections:
------------------------
The System.Collections namespace contains classes and interfaces that define complex data structures such as lists, queues, hash tables and dictionaries.

System.Data:
----------------
The System.Data namespace contains classes that make up the ADO.Net Architecture.  The ADO.NET architecture allows you to build components that can be used to insert, modify and delete data from multiple data sources.

System.Diagnostics:
-------------------------
The System.Diagnostics namespace contain classes that are used to interact with the system processes.

System.IO:
----------------
The System.IO namespace contain classes that enable you to read and write to data streams and files.

System.Web:
------------------
The System.Web namespace provides classes and interfaces that allow communication between the browser and the server.

User-Defined Namespaces:
----------------------------------
Making use of namespace in ourcode will reduce the complexities, when we want to re-use our code in some other applications.  In place of taking more number of classes in the project.  We can take help of  namespace

Example of Namespace:
--------------------------------
using System;
using trial1;
namespace trial
{
public class demo
{
public void display()
     {
       Console.WriteLine("Aptech Computer Education");
                    }

                   }
}
namespace trial1
{
public class demo
           

   {
                public void display()
                    {
Console.WriteLine("We Change Lives");
                                     }
                  }
}
class test
{
static void Main()
                  {
                   trial.demo d=new trial.demo();
      d.display();
           demo d1=new demo();
       //trial1.demo d1=new trial1.demo();
              d1.display();
                  }
}

Example of Namespace:
--------------------------------
using System;
using Students;

namespace Students
{
class StudentDetails
{
string sname="Scott";
int sno=101;

public StudentDetails()
{
Console.WriteLine("Student Name: "+sname);
Console.WriteLine("Student ID: "+sno);
}
}
}
namespace Examination
{
class ScoreReport
{
public string subject="Maths";
public int marks=80;

static void Main()
{
StudentDetails S=new StudentDetails();
ScoreReport S1=new ScoreReport();

Console.WriteLine("Subject: "+S1.subject);
Console.WriteLine("Marks: "+S1.marks);
}
}
}
===============================================================

Creating DLL Files:
===================
Differences between dll and exe file
--------------------------------------------
DLL:
--------
1. Dll stands for dynamic link library file.
2. It doesn't contain main method.
3. It provides the reusability.
4. We can't execute the dll file.

EXE:
-------
1. exe stands for executable file.
2. It contains main method.
3. We can execute this file and we will get output.

Example I(Save below program as adl.cs)
---------------------------------------------------------
using System;
namespace myarith
{
public class mymath
{
public int sum(int x,int y)
{
return x+y;
}
}
}


Converting above file into dll file:
---------------------------------------------
csc /out:adl.dll /t:library adl.cs


Using above dll file in another program(adl1.cs):
------------------------------------------------------------
using System;
using myarith;
class test
{
static void Main()
{
mymath m=new mymath();
Console.WriteLine("Enter two numbers");
int a=Convert.ToInt16(Console.ReadLine());
int b=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("The Sum of {0} & {1} is : {2} ",a,b,m.sum(a,b));
                 }
}

Compiling above program using dll file:
-----------------------------------------------------
csc /r:adl.dll adl1.cs

Executing above file:
----------------------------
adl1

Syntaxes of Converting Dll files:
----------------------------------------
Converting into DLL File:

Syntax:
csc /out:filename.dll /t:library filename.cs
eg:- csc /out:adl.dll /t:library adl.cs

Using the Converted dll:-
Syntax:
csc /r:filename.dll filename.cs
eg:- csc /r:adl.dll adl1.cs


==================================================


Exceptions:
==========================================================
Exceptons are run-time errors that may cause a program to be abruptly terminated.  Exception handling is a process of handling these run-time errors.  Handling an exception refers to the action to be taken when an error occurs in order to save the program from being prematurely terminated.  In C#, two kinds of Exceptions

1. System-level Exceptions
2. Application-level Exceptions

1. System-level Exceptions:-
------------------------------------
System-level exceptions are the exceptions thrown by the system.  These exceptions are thrown by the CLR.  For example, exceptions thrown due to failure in database connection or network connection are system-level exceptions.

2. Application-level Exceptions:-
------------------------------------------
Application-level exceptions are thrown by user-created applications.  For example, exceptions thrown due to arithmetic operations or referencing any null object are application-level exceptions.

Properties of the "Exception" class:-
------------------------------------------------
The System.Exception class is the base class that allows you to handle all exceptions in C#.  This means that all exceptions in C# inherit the System.Exception class.

Message:
-----------
Displays a message which indicates the reason for the exception.

Source:
-----------
Provides th name of the application or the object that caused the exception.

StackTrace:
---------------
Provides exception details on the stack at the time the exception was thorwn.

InnerException:
--------------------
Returns the Exception instance that caused the current exception.

Exception Classes:
---------------------------
System.ArithmeticException:
--------------------------------------
This exception is thorwn for problems that occur due to airhmetic or casting and conversion operations.

System.ArgumentException:
------------------------------------
This exception is thrown when one of the arguments does not match the parameter specifications of the invoked method.

System.ArrayTypeMismatchException:
---------------------------------------------------
This exception is thrown when an attempt is made to store data in an array whose type is incompatible with the type of the array.

System.DivideByZeroExcepton:-
-----------------------------------------
This exception is thrown when an attempt is made to divide a numeric value by zero.

System.IndexOutOfRangeException:
------------------------------------------------
This exception is thrown when an attempt is made to store data in an array using an index that is less than zero or outside the upper bound of the array.

System.InvalidCastException:
----------------------------------------
This exception is thrown when an explicit conversion from the base type or interface type to another type fails.

System.ArgumentNullException:-
-------------------------------------------
This exception is thrown when a null reference is passed to an argument of a method that does not accept null values.

System.NullReferenceException:
--------------------------------------------
This exception is thrown when you try to assign a value to a null object.

System.OutOfMemoryException:
------------------------------------------
This exception is thrown when there is not enough memory to allocate to an object.

System.OverflowException:
------------------------------------
This exception is thrown when the result of an arithmetic, casting or conversion operation is too large to be stored in the destination object or variable.

System.StackOverflowException:-
---------------------------------------------
This exception is thrown when the stack runs out of space due to having too many pending method calls.

System.Data.DataException:-
---------------------------------------
This exception is thrown when errors are generated while using the ADO.Net components.

System.FomatException:-
---------------------------------
This exception is thrown when the format of an argument does not match the format of the parameter data type of the invoked method.

System.IO.IOException:
-------------------------------
This exception is thrown when any I/O error occurs while accessing information using streams, files and directories.


Syntax:
----------
try
{
      // statements that might raise exception
}
catch(Exception ex)
{
      // statements for handling the exception
}
finally
{
      //statements that are mandatory
}


Catching Exceptions:
----------------------------
Exception handling is implemented using the try-catch blocks.  The try block contains the statements that might generate exceptions.  When these exceptions are thrown, the required actions are performed using the catch block.  The catch block is only executed if the try block throws an exception.

The "throw" statement:
--------------------------------
The throw statement takes an instance does not refer to valid exception class,
the C# compiler generates an error.  When you throw an exception using the throw keyword, the exception is handled by the catch block.

The "finally" Statement:
---------------------------------
The try block raises an exception, the catch block is executed and the rest of the statements in the try block are ignored.  But, sometimes it becomes mandatory to execute some statements irrespective of whether an exception is raised or not.  In such cases, a finally block is used.eg: closing a file, closing a database connection etc.


Example of ArrayTypeMismatchException:
---------------------------------------------------------
using System;
class Test
{
static void Main()
{
string[] names={"Ajay","Rohith","Rajesh"};
int[] id={10,20,30};
double[] salary={1000,2000,3000};
float[] bonus=new float[3];

try
{
salary.CopyTo(bonus,0);

}
/* catch(ArrayTypeMismatchException e)
{
Console.WriteLine("You have an error: "+e);
} */

catch(Exception e)
{
Console.WriteLine("You have an error: "+e);
}
}
}
---------------------------------------------------------------------------------------------------
Example of NullReferenceException:
------------------------------------------------------

using System;
class Employee
{
 string empname;
 int empid;

public Employee()
{
empname="Scott";
empid=101;
}

static void Main()
{
Employee e=new Employee();
Employee eobj=e;
e=null;

try
{
Console.WriteLine("Employee Name: "+eobj.empname);
Console.WriteLine("Employee No: "+eobj.empid);
}
/*catch(NullReferenceException ex)
{
Console.WriteLine("Error: " +ex);
}*/
catch(Exception ex)
{
Console.WriteLine("Error: " +ex);
}
}
}

----------------------------------------------------------------------------------------------------------
Example of DivideByZeroException:-
----------------------------------------------------------------

using System;
class Test
{
static void Main()
{
int x,y,z;
Console.WriteLine("Enter any No to x: ");
x=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter any No to y: ");
y=Convert.ToInt16(Console.ReadLine());

try
{
z=x/y;
Console.WriteLine("The Result is {0}",z);
}



/* catch(DivideByZeroException ex)
{
Console.WriteLine("Number cannot be divided by zero"+ex);
} */
catch(Exception ex)
{
//Console.WriteLine("Number cannot be divided by zero"+ex);
Console.WriteLine(ex.Message);
}
}
}

-----------------------------------------------------------------------------------------------------------
Example of FormatException:
-------------------------------------------------------
using System;
class Test
{
static void Main()
{
int x,y,z;
Console.WriteLine("Enter any No to x: ");
x=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter any No to y: ");
y=Convert.ToInt16(Console.ReadLine());

try
{
z=x+y;
Console.WriteLine("The Result is {0}",z);
}

catch(FormatException ex)
{
Console.WriteLine(ex.Message);
}

catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

---------------------------------------------------------------------------------------------------------
Custom Exceptions:
--------------------------
Custom exceptions are user-defined exceptions that allow users to handle system and application-specific runtime errors.  Custom exceptions can be implemented by creating a new class that is derived from the Exception of SystemException or ApplicationException class.

Example of Custom Exceptions:-
-----------------------------------------

using System;
class Test:Exception
{
public Test(string msg):base(msg)
{

}
static void Main()
{
int x=133;
int y;
int result=0;
Console.WriteLine("Enter the value of y: ");
try
{
y=Convert.ToInt32(Console.ReadLine());
if(y == 0)
{
throw new Test("Zero not allowe here");
}
if(y < 0)
{
throw new Test("Please Enter Positive Value");
}

Console.WriteLine("You entered: " + y.ToString());

result=x/y;
}

catch(Test ex)
{
Console.WriteLine("Error: "+ex.Message);
}

catch(Exception objex)
{
Console.WriteLine("Error..." +objex.Message);
}
Console.WriteLine("Result of division: "+result);
}
}

=================================================================
Delegates:
===============================================

Introduction to Delegates:
-----------------------------------
Delegates are objects that contain references to methods that need to be invoked instead of containing the actual method names.  Using delegates, you can call any method, which is identified only at runtime.  A delegate is like having a general method name that points to various methods at different times and invokes the required method at run-time.  In C#, invoking a delegate will execute the referenced method at run-time.

To associate a delegate with a particular method, the method must have the same return type and parameter type as that of the delegate.

Features and Benefits:
--------------------------------
Delegates in C#  have some features that distinguish them from normal methods.

i. Methods can be passed as parameter to  a delegate.  In addition, a delegate can accept a block of code as a parameter.  Such blocks are referred to as anonymous methods because they have no method name.

ii. A delegate can invoke multiple methods simultaneously.  This is known as multicasting.

iii.  A delegate can encapsulate static methods.

There are three steps in using delegates.

1.Defining a Delegate.
2.Instantiating a Delegate
3.Using a Delegate.


Declaring Delegates:
-------------------------------
Delegates in C# are declared using the delegate keyword followed by the return type and the parameters of the referenced method.  Declaring a delegate is quite similar to declaring a method except that there is no implementation.  Thus, the declaration statement must end with a semi-colon(;).

eg:
public delegate int calc(int x, int y);

2.Instantiating a Delegate:
--------------------------------------
The delegate to instantiate the delegate and associate it with the required method.  Here, you must create an object of the delegate.  An object of delegate is created using the new keyword.  This object takes the name of the method as a parameter and this method has a similar signature as that of the delegate.  The created object is used to invoke the associated method at run-time.

3.Using a Delegate:-
-------------------------
A delegate can be declared either before creating the class (having the method to be referenced) or can be defined within the class.  There are four steps to implement delegated in C#.
i. Declare a delegate
ii. Create the method to be referenced by the delegate.
iii. Instantiate the delegate.
iv. Call the method using the object of the delegate.

Example 1:
--------------------
using System;
class test
{
public delegate int deleme(int a,int b);
class maths
{
public int addme(int a,int b)
{
return(a+b);
}

public int subme(int a,int b)
{
return(a-b);
}
}
class subject
{
static void Main()
{
deleme deleobj;
maths m=new maths();
deleobj=new deleme(m.subme);
  deleobj=new deleme(m.addme);
int t=deleobj(5,2);
int t1=deleobj(10,5);

System.Console.WriteLine(" Subtraction is {0}",t);
System.Console.WriteLine(" Sum  {0} ",t1);
  }
}
}
----------------------------------------------------------------------------------------------------------
// Working with Two Delegates but executing One delegate only

using System;
delegate void dlgsimple();
delegate double Addition(double x,double y);
class Exercise
{
private static void Welcome()
{
Console.WriteLine("Welcome to the Wonderful world of C# Program");
}
private static double plus(double a,double b)
{
return a+b;
}
static int Main()
{
dlgsimple Announce=new dlgsimple(Welcome);
Announce();
return 0;
}
}

--------------------------------------------------------------------------------------------------------

//Multiple Delegates

using System;
delegate void dlgsimple();
delegate double Addition(double a,double b);
class Exercise
{
private static void Welcome()
{
Console.WriteLine("Welcome to the Wonderful world of C# Program");
}
private static double plus(double a,double b)
{
//double a=248.10,b=200.10;
double c=a+b;
return c;
}

static int Main()
{
double a,b;
dlgsimple Announce=new dlgsimple(Welcome);
Addition Add=new Addition(plus);
Announce();
Console.WriteLine("Enter two numbers");
a=Convert.ToDouble(Console.ReadLine());
b=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Result is: {0}",Add(a,b));

//Console.WriteLine("\n248.10 + 200.10={0}",Add());

return 0;
}
}
--------------------------------------------------------------------------------------------------------
Events:
====================================

Events:
---------
Consider a group of people at a party playing Bingo.  When a number is called, the participants check if the number is on their cards whereas the non-participants go about their business, enjoying other activities.  If this situation is analysed from a programmer's perspective, the calling of the number corresponds to the occurrence of an event.  The notification about the event is given by the announcer.  Here, the people playing the game are paying attention(subscribing) to what the announcer(the source of the event) has to say (notify).

Similarly, in C#, events allow an object(source of the event) to notify other objects(subscribers) about the event(a change having occurred).

Features:
-------------
An event is a user-generated or system-generated action that enables the required objects to notify other objects or classes to handle the event.

* They can be declared in classes and interfaces.
* They can be declared as abstract or sealed.
* They can be declared as virual.
* They are implemented using delegates.

Events can be used to perform customized actions that are not already supported by C#.  Events are widely used in creating Graphical User Interface(GUI) based applications where events such as selecting an item from a list and closing a window are tracked.

Creating and Using Events:-
-------------------------------------
In C#, events are created using delegates.  Delegates are widely used for events handling.  There are five steps for implementing events in C#.

1. Define a public delegate for the event.
2. Create the event using the delegate.
3. Subscribe to listen and hanle the event.
4. Raise the event.

Events use delegates to call methods in objects that have subscribed to the event.  When an event containing a number of subscribers is raised, many delegates will be invoked.

Declaring Events:
-------------------------
An event declaration consists of two steps, creating a delegate and creating the event.  A delegate is declared using the delegate keyword.  The delegate passes the paramaters of the appropriate method to be invoked when an event is generated.  This method is known as the event handler.  The event is then declared using the event keyword followed by the name of the delegate and the name of the event.  This declaration associates the event with the delegate.

Subscribing to Events:
-----------------------------
An object can subscribe to an event only if the event exists.  To subscribe to the event, the object adds a delegate that calls a mehod when the event is raised.  This takes place by associating the event handler to the created event using the += addition assignment operator.  This is known as subscribing to an event.

To unsubscribe from an event, use the -= subtraction assignment operator.

Raising Events:
--------------------
An event is raised to notify all the objects that have subscribed to an event.  Events are either raised by the user or the system.  Once an event is generated, all the associated event handlers are executed.  The delegate calls all the handlers that have been added to the event.  However, before raising an event, it is important for you to create handlers and thus make sure that the event is associated to the appropriate event handlers.  If the event is not associated to any event handler, the declared event is considered to be null.

-----------------------------------------------------------------------------------
Example 1:
----------------------------------------------------------------
using System;
delegate void dlgsimple();
class exercise
{
public static event dlgsimple simply;
public static void welcome()
{
Console.WriteLine("Hello Friends");
}
public static void sayhello()
{
simply();
}
static void Main()
{
simply += new dlgsimple(welcome);
sayhello();

}
}
------------------------------------------------------------------------------------------------------


using System;
using System.Drawing;
using System.Windows.Forms;

// custom delegate
public delegate void StartDelegate();

class EventDemo : Form
{
     // custom event
     public event StartDelegate StartEvent;

     public EventDemo()
     {
         Button clickMe = new Button();

         clickMe.Parent = this;
         clickMe.Text = "Click Me";
         clickMe.Location = new Point(
            (ClientSize.Width - clickMe.Width) /2,
            (ClientSize.Height - clickMe.Height)/2);

        // an EventHandler delegate is assigned
        // to the button's Click event
         clickMe.Click += new EventHandler(OnClickMeClicked);

         // our custom "StartDelegate" delegate is assigned
         // to our custom "StartEvent" event.
         StartEvent += new StartDelegate(OnStartEvent);

         // fire our custom event
         StartEvent();
}

    // this method is called when the "clickMe" button is pressed
public void OnClickMeClicked(object sender, EventArgs ea)
{
  MessageBox.Show("You Clicked My Button!");
}

     // this method is called when the "StartEvent" Event is fired
     public void OnStartEvent()
     {
         MessageBox.Show("I Just Started!");
     }

     static void Main(string[] args)
     {
         Application.Run(new EventDemo());
     }
}

================================================================
COLLECTIONS AND GENERICS
================================================================
Collections:-
----------------
 The System.Collections namespace consists of collections of arrays, lists, hashtables and dictionaries.  The System.Collections.Generic namespace consists of generic collections, which provide better type safety and performance.  The collection is a set of related data that may not necessarily belong to the same data type.  It can be set or modified dynamically at run-time.

Differences between Arrays and Collection:
----------------------------------------------------------
Array:
----------
* Cannot be resized at runtime.
* The individual elements are of the same data type.
* Do not contain any methods for operations on elements.

Collection:
--------------
* Can be resized at runtime.
* The individual elements can be  of different data types.
* Contain methods for operations on elements.

Classes of System.Collections namespace:
-------------------------------------------------------
ArrayList:
--------------
The array list,  is a type very similar to a traditional array. It is simply an improvement in the usability of traditional arrays. Most languages require you to size arrays when you create them. That size is fixed for the lifetime of the array. An ArrayList is an array wrapper that allows the size to dynamically increase as needed. You do not need to know the array's size at the time when you create the ArrayList, and the array is not limited in size.

Stack:-
-----------
Provides a collection that follows the Last-In-First-Out (LIFO) principle, which means the last item inserted in the collection will be removed first.

Queue:
----------
Provides a collection that follows the First-In-First-Out (FIFO) principle, which means the first item inserted in the collection will be removed first.

Hashtable:
--------------
Provides a collection of key and value pairs that are arranged based on the hash code of the key.

SortedList:
--------------
Provides a collection of key and value pairs where the items are sorted based on the keys.

Interfaces of System.Collections namespace:
---------------------------------------------------------
ICollection:
---------------
Specifies the size and synchronization methods for all collections.

IEnumerator:
-----------------
Supports iteration over the elements of the collection.

IList:
-------
Represents a collection of items that can be accessed by their index number.

System.Collections.Generic namespace:
----------------------------------------------------
System.Collection.Generic namespace is similar to the System.Collection namespace as both allow you to create collections.  However, generic collections are type-safe.

Classes of System.Collections.Generic namespace:
-----------------------------------------------------------------
List<T>:
-----------
Provides a generic collection of items that can be dynamically resized.

Stack<T>:
-------------
Provides a generic collection that follows  the Last-In-First-Out (LIFO) principle, which means that the last item inserted in the collection will be removed first.

Queue<T>:
----------------
Provides a generic collection that follows the First-In-First-Out(FIFO) principle, which means that the first item inserted in the collection will be removed first.

Dictionary<K,V>:
----------------------
Provides a generic collection of keys and values.

SortedDictionary<K,V>:
--------------------------------
Provides a generic collection of sorted key and value pairs that consist of items sorted according to their key.

LinkedList<T>:
----------------------
Implements the doubly linked list by storing elements in it.

Interfaces of System.Collections.Generic namespace:
----------------------------------------------------------------------
ICollection:
----------------
Defines methods to control the different generic collections.

IDictionary:
----------------
Represents a generic collection consisting of the key and value pairs.

IEnumerator:
------------------
Supports simple iteration over elements of a generic collection.

IList:-
--------
Represents a generic collection of items that can be accessed using the index position.

Example of ArrayList:
----------------------------------
 using System;
using System.Collections;
class Customers
{
static void Main()
{
ArrayList C = new ArrayList();
C .Add("prakash");
C .Add("pranav");
C .Add("Praveen");
C.Add("Vikash");
C.Add("Harish");
C.Add("Manasa");

Console.WriteLine("Total No. of Elements :" + C.Count);
Console.WriteLine("List of Customers ");


foreach(string names  in C)
{
Console.WriteLine("{0}",names);
}
C.Reverse();
Console.WriteLine("\n List of Customers after reversing: ");

foreach(string names in C)
{
Console.WriteLine("{0}",names);
}
C.Clear();
Console.WriteLine("Count after removing all elements: "+C.Count);
}
}
--------------------------------------------------------------------------------------------------------

Hashtable:-
-------------
Represents a collection of key/value pairs that are organized based on the hash code of the key.

Example of Hashtable:
------------------------------

using System;
using System.Collections;
class Authors
{
static void Main()
{
Hashtable H=new Hashtable();
H.Add("AU01","Vikash");
H.Add("AU02","Praveen");
H.Add("AU03","Anusha");
H.Add("AU04","Manasa");
H.Add("AU05","Gowthami");
H.Add("AU06","Harish");
H.Add("AU07","Kishore");
H.Add("AU08","ddgdgdgdgdgdg");
H.Add("AU09","ddg");

Console.WriteLine("Total No. of Elements : " + H.Count);
IDictionaryEnumerator obj=H.GetEnumerator();

Console.WriteLine("\nList of Authors");
Console.WriteLine("Author ID \t Name");

while(obj.MoveNext())
{
Console.WriteLine(obj.Key + "\t\t" + obj.Value);
}

if(H.Contains("AU01"))
{
Console.WriteLine("\n List contains author with id AU01");
}
else
{
Console.WriteLine("\n List does not contain author with id AU01");
}
}
}


---------------------------------------------------------------------------------------------------------
SortedList:-
--------------
The SortedList class consists of different methods and properties that represent key/value pairs that are sorted according to the key.

Example of SortedList:
---------------------------------

 using System;
using System.Collections;
class Countries
{
static void Main()
{
SortedList S = new SortedList();
S.Add("UK", "United kingdom");
S.Add("GER" , "Germay");
S.Add("USA", "United States of America");
S.Add("AUS", " Australia");

Console.WriteLine("Count : "+ S.Count);
Console.WriteLine("List of Countries \n");
Console.WriteLine("Country Code \t Name");


for(int i=0; i< S.Count ; i++)
{
Console.WriteLine(S.GetKey(i) + "\t\t " + S.GetByIndex(i));
}

S.RemoveAt(1);
Console.WriteLine("\n list of countries after removing element at index ");

Console.WriteLine("Country Code \t Name");

for(int i=0; i < S.Count; i++)
{
Console.WriteLine(S.GetKey(i)  + "\t\t" + S.GetByIndex(i));

}
}
}

----------------------------------------------------------------------------------------------------------
Example of Dictionary:
------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;

class Car
{
static void Main()
{
Dictionary <int, string> D = new Dictionary <int, string>();

D.Add(201,"Gear Box");
D.Add(220, "Oli Filter ");
D.Add(330, "Engine");
D.Add(305, "Radiator");
D.Add(303, "Steering");

Console.WriteLine("Dictionary class contains values of type");
Console.WriteLine(D.GetType());

Console.WriteLine("Keys \t\t Values");
Console.WriteLine("______________________________________");
IDictionaryEnumerator objDE = D.GetEnumerator();

while(objDE.MoveNext ())
{
Console.WriteLine(objDE.Key.ToString() + "\t\t" + objDE.Value);
}
         }
}
-----------------------------------------------------------------------------------------------------
Example of LinkedList:-
---------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;

class Student: IEnumerable
{
LinkedList<string> objList =new LinkedList<string> ();

public void StudentDetails()
{

objList.AddFirst("prakash");
objList.AddFirst("john");
objList.AddFirst("peter");
objList.AddFirst("james");
objList.AddFirst("james");
objList.AddFirst("james");
objList.AddFirst("patrick");

Console.WriteLine("Number of elements stored in the list :"+objList.Count);
}

public void Display(string name)
{
LinkedListNode<string> objNode;

int count =0;

for( objNode = objList.First; objNode != null; objNode = objNode.Next)
{

if(objNode.Value.Equals(name))
{
count++;
}
}
Console.WriteLine("The value "+ name +" appears "+ count + " times in the list");
}

 public IEnumerator GetEnumerator()
{
return objList.GetEnumerator();
}

static void Main()
{
Student objStudent = new Student();
objStudent.StudentDetails();
foreach (string str in objStudent)
{
Console.WriteLine(str);
}
objStudent.Display("jamesdgfd");
}
}
-----------------------------------------------------------------------------------------------------------
Example of DictionaryBase Class:
--------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

class Employee : DictionaryBase
{
public void Add(int id, string name)
{
Dictionary.Add(id, name);
}
public void OnRemove(int id)
{
Console.WriteLine("Your are going to delete record containing id:"+id);
Dictionary.Remove(id);
}
public void GetDetails()
{
IDictionaryEnumerator objEnumerate = Dictionary.GetEnumerator();
while (objEnumerate.MoveNext())
{
Console.WriteLine(objEnumerate.Key.ToString() + "\t\t" + objEnumerate.Value);
}
}

static void Main()
{
Employee objEmployee = new Employee();
objEmployee.Add(102, "John");
objEmployee.Add(105, "james");
objEmployee.Add(106, "Peter");

Console.WriteLine("original values stored in Dictionary");

objEmployee.GetDetails();
objEmployee.OnRemove(106);
Console.WriteLine("Modified values stored in Dictionary");
objEmployee.GetDetails();
}
}

=================================================
/* Attributes:-
------------------------------------------------------------

      One of the most powerful capabilities of CSharp is its flexibility.  Attributes are such features.  With attributes CSharp provides a convenient technique that handle task such as changing the behaviour of a method at run-time performing compiletime operations are may be event handling unmanaged code.  Basically an attribute is a declarative tab that can be used to provide information to the run-time above the behaviour of CSharp elements such as classes and assemblies.  They are used to add Metadata(data describing data) to these  classes and assemblies. */

using System;
class Demo
{
 [Obsolete("This method cannot be used in Next Version" )]
//[Obsolete()]
public static void Msg(string msg)
{
Console.WriteLine(msg);
}
static void Main()
{
Msg("Trying out Attributes");

}

}


================================================

/* The System.IO Namespace:-
The System.IO Namespace provides plenty of classes for file/stream input/output.  The namespace also supplies the classes titled File and Directory that make it possible to operate files and directories. Operations such as copying,moving, renaming and deleting cab easily done.  */

using System;
using System.IO;

class Test
{

static void Main()
{
FileInfo[] F;
// FileInfo[] F1;
DirectoryInfo DI=new DirectoryInfo(".");

F=DI.GetFiles("*.cs" );
//F1=DI.GetFiles("*.txt" );
foreach(FileInfo t in F)
{
Console.WriteLine(t);
}

/* foreach(FileInfo t in F1)
{
Console.WriteLine(t);
} */
}
}


-----------------------------------------------------------------------------

using System;
using System.IO;

class Test
{

static void Main()
{
Console.WriteLine(@"Creatin' Directory C:\Scooby ...");
Directory.CreateDirectory(@"C:\jeelz");
DateTime CreationDate=Directory.GetCreationTime(@"C:\Scooby");

Console.WriteLine("Directory Created on: " +CreationDate.ToString());
}
}


=============================================
Multi Threading:
======================

Mutli Tasking:
-------------------
Performs Several tasks at once.  Computers can performs many tasks concurrently.  Download a file, print a file, receive email etc.  .Net offers primitives for turning a program into separate, independently-running subtasks.  Each subtask is thread.

Example I
-----------------
using System;
class A37
{
public void printNum()
{
int i=0;
while(i<=5)
{
Console.WriteLine(i);
i++;
}
}
public static void Main(String[] args)
{
A37 t=new A37();
t.printNum();
t.printNum();
}
}
---------------------------------------------------------------------

Example
---------------

using System;
using System.Threading;
public class test
{
static void Main()
{

counter c=new counter();
ThreadStart job=new ThreadStart(c.count);
Thread thread=new Thread(job);
thread.Start();
for(int i=0;i<5;i++)
{
Console.WriteLine("Main thread: {0}",i);
Thread.Sleep(500);
                 }
           }
    }
public class counter
{
public void count()
{

for(int i=0;i<10;i++)
{
Console.WriteLine("Other thread : {0}",i);
Thread.Sleep(1000);
                  }
           }
}









































































No comments:

Post a Comment

PHP Notes

The Characteristics of PHP:- ----------------------------------- 1.PHP is a high level programming language. 2.It is a server-side scrip...