रविवार, 6 नवंबर 2016

Simple way of C# :part 4

1. STRINGS
In C#, you can use strings as array of characters. However, more common practice is to use the string keyword to declare a string variable. The string keyword is an alias for theSystem.String class.
Creating a String Object:
You can create string object using one of the following methods:
 By assigning a string literal to a String variable
 By using a String class constructor
 By using the string concatenation operator (+)
 By retrieving a property or calling a method that returns a string
 By calling a formatting method to convert a value or an object to its string representation
The following example demonstrates this:

using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname); 
//by using string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey() ;
}
}
}
========================================================
Methods of the String Class:
The String class has numerous methods that help you in working with the string objects. The following table provides some of the most commonly used methods: Sr. No. Methods
public static int Compare( string strA, string strB )
Compares two specified string objects and returns an integer that indicates their relative position in the sort order.
public static int Compare( string strA, string strB, bool ignoreCase )
Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores case if the Boolean parameter is true.
public static string Concat( string str0, string str1 )
Concatenates two string objects.
4 public static string Concat( string str0, string str1, string str2 )
Concatenates three string objects.
public static string Concat( string str0, string str1, string str2, string str3 )
Concatenates four string objects.
public bool Contains( string value )
Returns a value indicating whether the specified String object occurs within this string.
public static string Copy( string str )
Creates a new String object with the same value as the specified string.
public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )
Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters.
public bool EndsWith( string value )
Determines whether the end of the string object matches the specified string.
10 public bool Equals( string value )
Determines whether the current String object and the specified String object have the same value.
11 public static bool Equals( string a, string b )
Determines whether two specified String objects have the same value.
12 public static string Format( string format, Object arg0 )
Replaces one or more format items in a specified string with the string representation of a specified object.
13 public int IndexOf( char value )
Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.
14 public int IndexOf( string value )
Returns the zero-based index of the first occurrence of the specified string in this instance.
15 public int IndexOf( char value, int startIndex )
Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting search at the specified character position.
16 public int IndexOf( string value, int startIndex )
Returns the zero-based index of the first occurrence of the specified string in this instance, starting search at the specified character position.
17 public int IndexOfAny( char[] anyOf )
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.
18 public int IndexOfAny( char[] anyOf, int startIndex )
Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting search at the specified character position.
19 public string Insert( int startIndex, string value )
Returns a new string in which a specified string is inserted at a specified index position in the current string object.
20 public static bool IsNullOrEmpty( string value )
Indicates whether the specified string is null or an Empty string.
21 public static string Join( string separator, params string[] value )
Concatenates all the elements of a string array, using the specified separator between each element.
22    public static string Join( string separator, string[] value, int startIndex, int count )
Concatenates the specified elements of a string array, using the specified separator between each element.
23 public int LastIndexOf( char value )
Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.
24 public int LastIndexOf( string value )
Returns the zero-based index position of the last occurrence of a specified string within the current string object.
25 public string Remove( int startIndex )
Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
26 public string Remove( int startIndex, int count )
Removes the specified number of characters in the current string beginning at a specified position and returns the string.
27 public string Replace( char oldChar, char newChar )
Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.
28 public string Replace( string oldValue, string newValue )
Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.
29 public string[] Split( params char[] separator )
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.
30 public string[] Split( char[] separator, int count )
Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.
31 public bool StartsWith( string value )
Determines whether the beginning of this string instance matches the specified string.
32 public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object.
33 public char[] ToCharArray( int startIndex, int length )
Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.
34 public string ToLower()
Returns a copy of this string converted to lowercase.
35 public string ToUpper()
Returns a copy of this string converted to uppercase.
36 public string Trim()
Removes all leading and trailing white-space characters from the current String object.
You can visit MSDN library for the complete list of methods and String class constructors.
Example:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:

This is test and This is text are not equal.

String Contains String:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
132
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}
}
==================================================
When the above code is compiled and executed, it produces the following result:
The sequence 'test' was found.
Joining Strings:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"};
string str = String.Join("\n", starray);
Console.WriteLine(str);
}
Console.ReadKey() ;
}
}
==================================================

2. STRUCTURES
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:
 Title
 Author
 Subject

 Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author; 17. STRUCTURES
public string subject;
public int book_id;
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}

}
======================================================
Features of C# Structures:
You have already used a simple structure named Books. Structures in C# are quite different from that in traditional C or C++. The C# structures have the following features:
 Structures can have methods, fields, indexers, properties, operator methods, and events.
 Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and connot be changed.
 Unlike classes, structures cannot inherit other structures or classes.
 Structures cannot be used as a base for other structures or classes.
 A structure can implement one or more interfaces.
 Structure members cannot be specified as abstract, virtual, or protected.
 When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
 If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.
Class versus Structure:
Classes and Structures have the following basic differences:
 classes are reference types and structs are value types
 structures do not support inheritance
 structures cannot have default constructor
In the light of the above discussions, let us rewrite the previous example:

using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}

}
==============================================

3. ENUMS
An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword.
C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
Declaring enum Variable : 
The general syntax for declaring an enumeration is:
enum <enum_name>
{
enumeration list

};
Where,
 The enum_name specifies the enumeration type name.
 The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0. For example:

enum Days { un, Mon, tue, Wed, thu, Fri, Sat };

Example:
The following example demonstrates use of enum variable:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)Days.Mon;
int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}

}
=========================================================
4. CLASSES
Defining a Class:
A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. Following is the general form of a class definition:
<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list) 
{
// method body
}
}
========================================================
Note:
 Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private.
Data type specifies the type of variable, and return type specifies the data type of the data the method returns, if any.
 To access the class members, you use the dot (.) operator.

 The dot operator links the name of an object with the name of a member.
The following example illustrates the concepts discussed so far:
using System;
namespace BoxApplication
{
class Box
{
public double length; // Length of a box
public double breadth; // Breadth of a box
public double height; // Height of a box
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}
}
==========================================================
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation :
A member function of a class is a function that has its definition or its prototype within the class definition similar to any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.
Member variables are the attributes of an object (from design perspective) and they are kept private to implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class:

using System;
namespace BoxApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box();
double volume;
// Declare Box2 of type Box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}" ,volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
Console.ReadKey();
}
}

}
=================================================

C# Constructors:
A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

A constructor has exactly the same name as that of the class and it does not have any return type.
A default constructor does not have any parameter but if you need, a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation as shown in the following example:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line(double len) //Parameterized constructor
{
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}
=================================================
When the above code is compiled and executed, it produces the following result:
Object is being created, length = 10
Length of line : 10
Length of line : 6

C# Destructors:
A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope. A destructor has exactly the same name as that of the class with a prefixed tilde (~) and it can neither return a value nor can it take any parameters.

Destructor can be very useful for releasing memory resources before exiting the program. Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor:
using System;
namespace LineApplication
{
class Line
{
private double length; // Length of a line
public Line() // constructor
{
Console.WriteLine("Object is being created");
}
~Line() //destructor
{
Console.WriteLine("Object is being deleted");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
}
}
}
==============================================
Static Members of a C# Class:
We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.
The following example demonstrates the use of static variables:
using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("Variable num for s1: {0}", s1.getNum());
Console.WriteLine("Variable num for s2: {0}", s2.getNum());
Console.ReadKey();
}
}
}
======================================================
You can also declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created. The following example demonstrates the use of static functions:

using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("Variable num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
===============================================
When the above code is compiled and executed, it produces the following result:
Variable num: 3

4. INHERITANCE
One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS Aanimal, dog IS-A mammal hence dog IS-A animal as well, and so on.
Base and Derived Classes:
A class can be derived from more than one class or interface, which means that it can inherit data and functions from multiple base classes or interfaces.
The syntax used in C# for creating derived classes is as follows:
<acess-specifier> class <base_class>
{
...
}
class <derived_class> : <base_class>
{
...

}

Consider a base class Shape and its derived class Rectangle:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}
=========================================================
When the above code is compiled and executed, it produces the following result:

Total area: 35

Initializing Base Class:
The derived class inherits the base class member variables and member methods. Therefore the super class object should be created before the subclass is created. You can give instructions for superclass initialization in the member initialization list.
The following program demonstrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle
{
private double cost;
public Tabletop(double l, double w) : base(l, w)
{ }
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
===========================================================
When the above code is compiled and executed, it produces the following result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

Multiple Inheritance in C#:
C# does not support multiple inheritance. However, you can use interfaces to implement multiple inheritance. The following program demonstrates this:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}
// Base class PaintCost
public interface PaintCost
{
int getCost(int area);
}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
Console.WriteLine("Total area: {0}", Rect.getArea());
Console.WriteLine("Total paint cost: Rs{0}" , Rect.getCost(area));
Console.ReadKey();
}
}
}
==============================================
When the above code is compiled and executed, it produces the following result:
Total area: 35

Total paint cost: Rs2450

5. POLYMORPHISM
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism , it is decided at run-time.
Static Polymorphism:
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are:
1. Function overloading
2. Operator overloading
Function Overloading:
You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type.
The following example shows using function print() to print different data types:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}
void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}
void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args)
{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C#");
Console.ReadKey();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C#

Dynamic Polymorphism:
C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
Here are the rules about abstract classes:
 You cannot create an instance of an abstract class
 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
The following program demonstrates an abstract class:
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle: Shape
{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * length);
166
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}
========================================================
When the above code is compiled and executed, it produces the following result:
Rectangle class area :
Area: 70

When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
Dynamic polymorphism is implemented by abstract classes and virtual functions.
The following program demonstrates this:
using System;
namespace PolymorphismApplication
{
class Shape
{
protected int width, height;
public Shape( int a=0, int b=0)
{
width = a;
height = b;
}
public virtual int area()
{
Console.WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{
}
public override int area ()
{
Console.WriteLine("Rectangle class area :");
return (width * height);
}
}
class Triangle: Shape
{
public Triangle(int a = 0, int b = 0): base(a, b)
{
}
public override int area()
{
Console.WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh.area();
Console.WriteLine("Area: {0}", a);
}
}
class Tester
{
static void Main(string[] args)
{
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
}
}
}
===============================================

6. OPERATOR OVERLOADING
You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Similar to any other function, an overloaded operator has a return type and a parameter list.
For example, go through the following function:

public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

The above function implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.

Implementing the Operator Overloading:
The following program shows the complete implementation:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box 
private double height; // Height of a box
public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}
========================================================
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable and Non-Overloadable Operators:
The following table describes the overload ability of the operators in C#:
1 +, -, !, ~, ++, --
These unary operators take one operand and can be overloaded.
2 +, -, *, /, %
These binary operators take one operand and can be overloaded.
3 ==, !=, <, >, <=, >=
The comparison operators can be overloaded
4 &&, ||   The conditional logical operators cannot be overloaded directly.
5 +=, -=, *=, /=, %=
The assignment operators cannot be overloaded.
6 =, ., ?:, ->, new, is, sizeof, typeof
These operators cannot be overloaded.

Example:
In the light of the above discussions, let us extend the preceding example, and overload few more operators:

using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
public static bool operator == (Box lhs, Box rhs)
{
bool status = false;
if (lhs.length == rhs.length && lhs.height == rhs.height
&& lhs.breadth == rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator !=(Box lhs, Box rhs)
{

bool status = false;
if (lhs.length != rhs.length || lhs.height != rhs.height
|| lhs.breadth != rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator <(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length < rhs.length && lhs.height
< rhs.height && lhs.breadth < rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator >(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length > rhs.length && lhs.height
> rhs.height && lhs.breadth > rhs.breadth)
{
status = true;
}
return status;

}
public static bool operator <=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length <= rhs.length && lhs.height
<= rhs.height && lhs.breadth <= rhs.breadth)
{
status = true;
}
return status;
}
public static bool operator >=(Box lhs, Box rhs)
{
bool status = false;
if (lhs.length >= rhs.length && lhs.height
>= rhs.height && lhs.breadth >= rhs.breadth)
{
status = true;
}
return status;
}
public override string ToString()
{
return String.Format("({0}, {1}, {2})", length, breadth, height);
}
}

class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
Box Box4 = new Box();
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
//displaying the Boxes using the overloaded ToString():
Console.WriteLine("Box 1: {0}", Box1.ToString());
Console.WriteLine("Box 2: {0}", Box2.ToString());
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2

volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
Console.WriteLine("Box 3: {0}", Box3.ToString());
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
//comparing the boxes
if (Box1 > Box2)
Console.WriteLine("Box1 is greater than Box2");
else
Console.WriteLine("Box1 is greater than Box2");
if (Box1 < Box2)
Console.WriteLine("Box1 is less than Box2");
else
Console.WriteLine("Box1 is not less than Box2");
if (Box1 >= Box2)
Console.WriteLine("Box1 is greater or equal to Box2");
else
Console.WriteLine("Box1 is not greater or equal to Box2");
if (Box1 <= Box2)
Console.WriteLine("Box1 is less or equal to Box2");
else
Console.WriteLine("Box1 is not less or equal to Box2");
if (Box1 != Box2)
Console.WriteLine("Box1 is not equal to Box2");

else
Console.WriteLine("Box1 is not greater or equal to Box2");
Box4 = Box3;
if (Box3 == Box4)
Console.WriteLine("Box3 is equal to Box4");
else
Console.WriteLine("Box3 is not equal to Box4");
Console.ReadKey();
}
}

}
=================================================
When the above code is compiled and executed, it produces the following result:
Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560
Box 3: (18, 20, 15)
Volume of Box3 : 5400
Box1 is not greater than Box2
Box1 is less than Box2
Box1 is not greater or equal to Box2
Box1 is less or equal to Box2
Box1 is not equal to Box2

Box3 is equal to Box4

7. INTERFACES
An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.

Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionalities.
Declaring Interfaces:
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration:

public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}

Example:
The following example demonstrates implementation of the above interface:

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

public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
date = d;
amount = a;
}
public double getAmount()
{
return amount;
}

public void showTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}

}
===============================================
When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012

Amount: 451900

8. NAMESPACES
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
Defining a Namespace:
A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace namespace_name
{
// code declarations
}

To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
namespace_name.item_name;
The following program demonstrates use of namespaces:

using System;
namespace first_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}

}
namespace second_space
{
class namespace_cl
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
=============================================
When the above code is compiled and executed, it produces the following result:
Inside first_space

Inside second_space

The using Keyword:
The using keyword states that the program is using the names in the given namespace. For example, we are using the System namespace in our programs. The class Console is defined there.We just write:
Console.WriteLine ("Hello there");
We could have written the fully qualified name as:
System.Console.WriteLine("Hello there");
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:
Let us rewrite our preceding example, with using directive:

using System;
using first_space;
using second_space;
namespace first_space
{
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class efg
{
public void func()
{

Console.WriteLine("Inside second_space");
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
================================================
When the above code is compiled and executed, it produces the following result:
Inside first_space

Inside second_space

Nested Namespaces:
You can define one namespace inside another namespace as follows:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}
======================================================
You can access members of nested namespace by using the dot (.) operator as follows:
using System;
using first_space;
using first_space.second_space;
namespace first_space
{
class abc
{
public void func()
{
Console.WriteLine("Inside first_space");
}
}
namespace second_space
{
class efg
{
public void func()
{
Console.WriteLine("Inside second_space");
}
}
}
}
class TestClass
{
static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}

}
================================================
When the above code is compiled and executed, it produces the following result:
Inside first_space

Inside second_space

9. PREPROCESSOR DIRECTIVES
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).

C# compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line.
Preprocessor Directives in C#:
The following table lists the preprocessor directives available in C#: 
1 #define: It defines a sequence of characters, called symbol.
2 #undef: It allows you to undefine a symbol.
3 #if: It allows testing a symbol or symbols to see if they evaluate to true.
4 #else: It allows to create a compound conditional directive, along with #if.
5 #elif: It allows creating a compound conditional directive.
6 #endif: Specifies the end of a conditional directive.
7 #line: It lets you modify the compiler's line number and (optionally) the file name         output for errors and warnings.
8 #error: It allows generating an error from a specific location in your code.
9 #warning: It allows generating a level one warning from a specific location in your      code.
10 #region: It lets you specify a block of code that you can expand or collapse when        using the outlining feature of the Visual Studio Code Editor.
11 #endregion: It marks the end of a #region block.

The #define Preprocessor:
The #define preprocessor directive creates symbolic constants.
#define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows:

#define symbol

The following program illustrates this:

#define PI
using System;
namespace PreprocessorDAppl
{
class Program
{
static void Main(string[] args)
{
#if (PI)
Console.WriteLine("PI is defined");
#else
Console.WriteLine("PI is not defined");
#endif
Console.ReadKey();
}
}

}
==============================================
When the above code is compiled and executed, it produces the following result:
PI is defined

Conditional Directives:
You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.
Syntax for conditional directive is:

#if symbol [operator symbol]...

Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator.
The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following:
 == (equality)
 != (inequality)
 && (and)
 || (or)
You can also group symbols and operators with parentheses. Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive.
The following program demonstrates use of conditional directives:

#define DEBUG
#define VC_V10
using System;
public class TestClass
{
public static void Main()
{
#if (DEBUG && !VC_V10)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V10)
Console.WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
Console.WriteLine("DEBUG and VC_V10 are defined");
#else
Console.WriteLine("DEBUG and VC_V10 are not defined");
#endif
Console.ReadKey();
}
}
=================================================
When the above code is compiled and executed, it produces the following result:

DEBUG and VC_V10 are defined

10. REGULAR EXPRESSIONS
A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.
Constructs for Defining Regular Expressions:
There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the follwoing links to find these constructs.
 Character escapes
 Character classes
 Anchors
 Grouping constructs
 Quantifiers
 Backreference constructs
 Alternation constructs
 Substitutions

 Miscellaneous constructs
Character Escapes:
These are basically the special characters or escape characters. The backslash character (\) in a regular expression indicates that the character that follows it either is a special character or should be interpreted literally.
The following table lists the escape characters:

1 \a : Matches a bell character, \u0007.
2 \b : In a character class, matches a backspace, \u0008.
3 \t :  Matches a tab, \u0009.
4 \r : Matches a carriage return, \u000D. (\r is not equivalent to the newline character,           \n.)    \r\n(\w+)
5 \v : Matches a vertical tab, \u000B.
6 \f : Matches a form feed, \u000C.
7 \n : Matches a new line, \u000A.
8 \e : Matches an escape, \u001B.
9 nnn : Uses octal representation to specify a character (nnn consists of up to three              digits).
10 \x nn : Uses hexadecimal representation to specify a character (nn consists of                exactly two digits).
11 \c X\c x : Matches the ASCII control character that is specified by X or x, where          X or x is the letter of the control character.
12 \u nnnn : Matches a Unicode character by using hexadecimal representation              (exactly four digits, as represented by nnnn).
13 \ : When followed by a character that is not recognized as an escaped character, matches that character.

Character Classes:
A character class matches any one of a set of characters. The following table describes the character classes:
1 [character_group] :  Matches any single character in character_group. By default,    the match is case-sensitive.
2 [^character_group] : Negation: Matches any single character that is not in                character_group. By default, characters incharacter_group are case-sensitive.
3 [ first - last ] : Character range: Matches any single character in the range from              first to last.
4   .   : Wildcard: Matches any single character except \n.
5 \p{ name } : Matches any single character in the Unicode general category or                      named block  specified by name.
6 \P{ name } : Matches any single character that is not in the Unicode general                       category or named block specified by name.
7 \w : Matches any word character.
8 \W  (Capital letter) : Matches any non-word character.
9 \s : Matches any white-space character.
10 \S (Capital letter) :  Matches any non-white-space character.
11 \d :  Matches any decimal digit.
12 \D  (Capital letter) : Matches any character other than a decimal digit.

Anchors Regular Expressions:
Anchors allow a match to succeed or fail depending on the current position in the string. The following table lists the anchors:
1  ^ : The match must start at the beginning of the string or line.
2 $ : The match must occur at the end of the string or before \n at the end of the line       or string.
3 \A : The match must occur at the start of the string.
4 \Z : The match must occur at the end of the string or before \n at the end of the string.
5 \z : The match must occur at the end of the string.
6 \G : The match must occur at the point where the previous match ended.
7 \b :The match must occur on a boundary between a \w(alphanumeric) and                   a\W(nonalphanumeric) character.
8 \B : The match must not occur on a\b boundary.

Grouping Constructs:
Grouping constructs delineate sub-expressions of a regular expression and capture substrings of an input string. The following table lists the grouping constructs:
1 ( subexpression ) : Captures the matched subexpression and assigns it a zero-based      ordinal number.
2 (?< name >subexpression) : Captures the matched subexpression into a named          group.
3 (?< name1 -name2 >subexpression) : Defines a balancing group definition.
4 (?: subexpression) : Defines a noncapturing group.
5 (?imnsx-imnsx:subexpression) : Applies or disables the specified options                   withinsubexpression.
6 (?= subexpression) : Zero-width positive lookahead assertion.
7 (?! subexpression) : Zero-width negative lookahead assertion.
8 (?< =subexpression) : Zero-width positive lookbehind assertion.
9 (?< ! subexpression) :  Zero-width negative lookbehind assertion.
10 (?> subexpression) : Nonbacktracking (or "greedy") subexpression.     

Quantifier :
Quantifiers specify how many instances of the previous element (which can be a character, a group, or a character class) must be present in the input string for a match to occur.
1   * : Matches the previous element zero or more times. 
2   + : Matches the previous element one or more times.
3   ? : Matches the previous element zero or one time. 
4   { n } : Matches the previous element exactly n times.
5   { n ,} : Matches the previous element at least n times.
{ n , m } : Matches the previous element at least n times, but no more than m times.
7 *? : Matches the previous element zero or more times, but as few times as possible.
8 +? : Matches the previous element one or more times, but as few times as possible.
9 ?? : Matches the previous element zero or one time, but as few times as possible.
10 { n }? : Matches the preceding element exactly n times.

11 { n ,}?      : Matches the previous element at least n times, but as few times as                           possible.
12 { n , m }?   : Matches the previous element between n and m times, but as few                times as possible.
Backreference Constructs:
Backreference constructs allow a previously matched sub-expression to be identified subsequently in the same regular expression.
The following table lists these constructs:
1 \ number  : Backreference. Matches the value of a numbered subexpression.
2 \k< name > : Named backreference. Matches the value of a named expression.

Alternation Constructs:
Alternation constructs modify a regular expression to enable either/or matching. The following table lists the alternation constructs:
1 | : Matches any one element separated by the vertical bar (|) character.
2 (?( expression )yes | no ) : Matches yes if expression matches; otherwise, matches          the optional no part. Expression is interpreted as a zero-width assertion.
3 (?( name )yes | no ) :  Matches yes if the named capture name has a match;                     otherwise, matches the optional no.

 Substitution : 
Substitutions are used in replacement patterns. The following table lists the substitutions:
1 $number : Substitutes the substring matched by group number.
2 ${name} : Substitutes the substring matched by the namedgroupname.
3 $$ :  Substitutes a literal "$".
4 $&: Substitutes a copy of the whole match.
5 $` :  Substitutes all the text of the input string before the match.
6  $' :  Substitutes all the text of the input string after the match.
7 $+ : Substitutes the last group that was captured.
8 $_   :   Substitutes the entire input string.

Miscellaneous Constructs : 
The following table lists various miscellaneous constructs:
1 (?imnsx-imnsx) : Sets or disables options such as case insensitivity in the middle           of a pattern.
2 (?#comment) :  Inline comment. The comment ends at the first closing parenthesis.
3 # [to end of line] : X-mode comment. The comment starts at an unescaped # and                continues to the end of the line.
The Regex Class:
The Regex class is used for representing a regular expression.It has the following commonly used methods:
public bool IsMatch( string input )
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
2  public bool IsMatch( string input, int startat )
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
public static bool IsMatch( string input, string pattern )
Indicates whether the specified regular expression finds a match in the specified input string.
public MatchCollection Matches( string input )
Searches the specified input string for all occurrences of a regular expression.
public string Replace( string input, string replacement )
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
6   public string[] Split( string input )
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

For the complete list of methods and properties, please read the Microsoft documentation on C#.
Example 1 :
The following example matches words that start with 'S':

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}

}
============================================
When the above code is compiled and executed, it produces the following result:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid

Suns

Example 2 :
The following example matches words that start with 'm' and ends with 'e':

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}

}
============================================
When the above code is compiled and executed, it produces the following result:
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage

measure

Example 3 : 
This example replaces extra white space:

using System;
using System.Text.RegularExpressions;
namespace RegExApplication
{
class Program
{
static void Main(string[] args)
{
string input = "Hello World ";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
}
}

}
==============================================
When the above code is compiled and executed, it produces the following result:
Original String: Hello World

Replacement String: Hello World      
Continue reading...........................................................................................................
============================================================
  Contect me to  if you are thinking making a website with low price.
Contect Email :  10julyRAJKUMAR@gmail.com
RAJ KUMAR
(Software Engg)

Simple way of C# :part 3

1. DECISION MAKING
Decision making structures requires the programmer to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

Following is the general from of a typical decision making structure found in most of the programming languages:
 (Decision Making  Chart )          
C# provides following types of decision making statements. Click the following links to check their detail.
if Statement:
An if statement consists of a boolean expression followed by one or more statements.
Syntax : 
The syntax of an if statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) is executed.

using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if (a < 20)
{
/* if condition is true then print the following */
Console.WriteLine("a is less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}
===============================================
if...else Statement:
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
Syntax
The syntax of an if...else statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */

}
If the boolean expression evaluates to true, then the if block of code is executed, otherwise else block of code is executed.

Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if (a < 20)
{
/* if condition is true then print the following */
Console.WriteLine("a is less than 20");
}
else
{
/* if condition is false then print the following */
Console.WriteLine("a is not less than 20");
}
Console.WriteLine("value of a is : {0}", a);
Console.ReadLine();
}
}
}
=============================================
When the above code is compiled and executed, it produces the following result:
a is not less than 20;

value of a is : 100

The if...else if...else Statement:
An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement.
When using if, else if and else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C# is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
===================================================
Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if (a == 10)
{
/* if condition is true then print the following */
Console.WriteLine("Value of a is 10");
}
else if (a == 20)
{
/* if else if condition is true */
Console.WriteLine("Value of a is 20");
}
else if (a == 30)
{
/* if else if condition is true */
Console.WriteLine("Value of a is 30");
}
else
{
/* if none of the conditions is true */
Console.WriteLine("None of the values is matching");
}
Console.WriteLine("Exact value of a is: {0}", a);
Console.ReadLine();
}
}

}
================================================
When the above code is compiled and executed, it produces the following result:
None of the values is matching

Exact value of a is: 100

Nested if Statements:
It is always legal in C# to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
Syntax:
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}

You can nest else if...else in the similar way as you have nested if statement.
Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
//* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if (a == 100)
{
/* if condition is true then check the following */
if (b == 200)
{
/* if condition is true then print the following */
Console.WriteLine("Value of a is 100 and b is 200");
}
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100

Exact value of b is : 200

Switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Syntax:
The syntax for a switch statement in C# is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}

The following rules apply to a switch statement:
 The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

 The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

 A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Flow Diagram
Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
================================================

When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B

The syntax for a nested switch statement is as follows:
switch(ch1)
{
case 'A':
printf("This A is part of outer switch" );
switch(ch2)
{
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */
}

Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
int a = 100;
int b = 200;
switch (a)
{
case 100:
Console.WriteLine("This is part of outer switch ");
switch (b)
{
case 200:
Console.WriteLine("This is part of inner switch ");
break;
}
break;
}
Console.WriteLine("Exact value of a is : {0}", a);
Console.WriteLine("Exact value of b is : {0}", b);
Console.ReadLine();
}
}
}
=================================================
When the above code is compiled and executed, it produces the following result:
This is part of outer switch
This is part of inner switch
Exact value of a is : 100

Exact value of b is : 200

The ? : Operator:
We have covered conditional operator ? : in previous chapter which can be used to replace if...else statements. It has the following general form:
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

2 .LOOPS
There may be a situation, when you need to execute a block of code several number of times. In general, the statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or a group of statements multiple times and following is the general from of a loop statement in most of the programming languages:

While Loop:
A while loop statement in C# repeatedly executes a target statement as long as a given condition is true.

The syntax of a while loop in C# is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20)
{
Console.WriteLine("value of a: {0}", a);
a++;
}
Console.ReadLine();
}
}

}
===============================================

For Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in C# is:

for ( init; condition; increment )

{
statement(s);

}
Here is the flow of control in a for loop:
1. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates.

Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* for loop execution */
for (int a = 10; a < 20; a = a + 1)
{
Console.WriteLine("value of a: {0}", a);
}
Console.ReadLine();
}
}

}
============================================

Do...While Loop:
Unlike for and while loops, which test the loop condition at the start of the loop, the do...while loop checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.


The syntax of a do...while loop in C# is:
do
{
statement(s);

}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the given condition becomes false.
Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
Console.WriteLine("value of a: {0}", a);
a = a + 1;
} while (a < 20);
Console.ReadLine();
}
}

}
================================================

Nested Loops:
C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.

The syntax for a nested for loop statement in C# is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C# is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C# is as follows:
do
{
statement(s);
do

{
statement(s);
}while( condition );

}while( condition );

Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100 :
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int i, j;
for (i = 2; i < 100; i++)
{
for (j = 2; j <= (i / j); j++)
if ((i % j) == 0) break; // if factor found, not prime
if (j > (i / j))
Console.WriteLine("{0} is prime", i);

}
Console.ReadLine();
}
}

}
=========================================
Loop Control Statements:
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C# provides the following control statements. Click the following links to check their details.
Break Statement:
The break statement in C# has following two usage:
1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in C# is as follows:
break;

Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* while loop execution */
while (a < 20)
{
80
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15)
{
/* terminate the loop using break statement */
break;
}
}
Console.ReadLine();
}
}
}
=========================================
Continue Statement:
The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control passes to the conditional tests.
The syntax for a continue statement in C# is as follows:
continue;

Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
82
do
{
if (a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
} while (a < 20);
Console.ReadLine();
}
}

}
======================================================
Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Hey! I am Trapped");
}
}
}
}
================================================
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but programmers more commonly use the for(;;) construct to signify an infinite loop.

3. ENCAPSULATION
Encapsulation is defined 'as the process of enclosing one or more items within a physical or logical package'. Encapsulation, in object oriented programming methodology, prevents access to implementation details.
Abstraction and encapsulation are related features in object oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.
Encapsulation is implemented by using access specifiers. An access specifier defines the scope and visibility of a class member. C# supports the following access specifiers:
 Public
 Private
 Protected
 Internal
 Protected internal
Public Access Specifier:

Public access specifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed from outside the class.
The following example illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
public double length;
public double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
========================================================
In the preceding example, the member variables length and width are declared public, so they can be accessed from the function Main() using an instance of the Rectangle class, named r.
The member function Display() and GetArea() can also access these variables directly without using any instance of the class.
The member functions Display() is also declared public, so it can also be accessed fromMain() using an instance of the Rectangle class, named r.

Private Access Specifier:
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members. Even an instance of a class cannot access its private members.
The following example illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
private double length;
private double width;
public void Acceptdetails()
{
Console.WriteLine("Enter Length: ");
length = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter Width: ");
width = Convert.ToDouble(Console.ReadLine());
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
==============================================
In the preceding example, the member variables length and width are declared private, so they cannot be accessed from the function Main(). The member functions AcceptDetails()and Display() can access these variables. Since the member functions AcceptDetails() andDisplay() are declared public, they can be accessed from Main() using an instance of the Rectangle class, named r.

Internal Access Specifier:
Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly. In other words, any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The following program illustrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
internal double length;
internal double width;
double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
=============================================

4. METHODS
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main.
To use a method, you need to:
 Define the method
 Call the method
Defining Methods in C#:
When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows:
<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
Method Body
}
Following are the various elements of a method:
 Access Specifier: This determines the visibility of a variable or a method from another class.
 Return type: A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void.
 Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class.
 Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

 Method body: This contains the set of instructions needed to complete the required activity.
Example:
class NumberManipulator 
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
...

}
=================================================
Calling Methods in C#:
You can call a method using the name of the method. The following example illustrates this:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
93
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();
//calling the FindMax method
ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
===========================================
When the above code is compiled and executed, it produces the following result:

Max value is : 200

Recursive Method Call:
A method can call itself. This is known as recursion. Following is an example that calculates factorial for a given number using a recursive function:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));
Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}
======================================================
When the above code is compiled and executed, it produces the following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Passing Parameters to a Method:
When method with parameters is called, you need to pass the parameters to the method. There are three ways that parameters can be passed to a method:
Passing Parameters by Value :
This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter.
The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument. The following example demonstrates the concept:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}
98
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */
n.swap(a, b);
Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}
}
}
========================================================
Passing Parameters by Reference :
A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
You can declare the reference parameters using the ref keyword. The following example demonstrates this:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;
Console.WriteLine("Before swap, value of a : {0}", a);
Console.WriteLine("Before swap, value of b : {0}", b);
/* calling a function to swap the values */
n.swap(ref a, ref b);
Console.WriteLine("After swap, value of a : {0}", a);
Console.WriteLine("After swap, value of b : {0}", b);
Console.ReadLine();
}
}
}
=========================================================
Passing Parameters by Output :
A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function. Output parameters are similar to reference parameters, except that they transfer data out of the method rather than into it.
The following example illustrates this:

using System;
 namespace CalculatorApplication
{
class NumberManipulator
{
public void getValue(out int x )
{
int temp = 5;
x = temp;
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
Console.WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */
n.getValue(out a);
Console.WriteLine("After method call, value of a : {0}", a);
Console.ReadLine();
}
}
}
============================================
The variable supplied for the output parameter need not be assigned a value. Output parameters are particularly useful when you need to return values from a method through the parameters without assigning an initial value to the parameter. Go through the following example, to understand this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void getValues(out int x, out int y )
{
Console.WriteLine("Enter the first value: ");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second value: ");
y = Convert.ToInt32(Console.ReadLine());
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a , b;
/* calling a function to get the values */
n.getValues(out a, out b);
Console.WriteLine("After method call, value of a : {0}", a);
Console.WriteLine("After method call, value of b : {0}", b);
Console.ReadLine();
}
}

}
========================================================

5. NULLABLES
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows:
< data_type> ? <variable_name> = null;
The following example demonstrates use of nullable data types:

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolval = new bool?();
// display the values
Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}",
num1, num2, num3, num4);

Console.WriteLine("A Nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
================================================
When the above code is compiled and executed, it produces the following result:
Nullables at Show: , 45, , 3.14157

A Nullable boolean value:

The Null Coalescing Operator (??) :
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this:

using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
========================================================
When the above code is compiled and executed, it produces the following result:
Value of num3: 5.34
Value of num3: 3.14157



6. ARRAYS
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contigeous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.



Declaring Arrays:
To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,
 datatype is used to specify the type of elements in the array.
 [ ] specifies the rank of the array. The rank specifies the size of the array.
 arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array:
Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. 15. ARRAYS
108
Array is a reference type, so you need to use the new keyword to create an instance of the array. For example,

double[] balance = new double[10];

Assigning Values to an Array:
You can assign values to individual array elements, by using the index number, like:
double[] balance = new double[10];
balance[0] = 4500.0;
You can assign values to the array at the time of declaration as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
You can also create and initialize an array as shown:
int [] marks = new int[5] { 99, 98, 92, 97, 95};
You may also omit the size of the array as shown:

int [] marks = new int[] { 99, 98, 92, 97, 95};
You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location:
int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

Accessing Array Elements:
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,

double salary = balance[9];
The following example demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays:

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
===================================================
Using the foreach Loop:
In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array.

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
/* initialize elements of array n */
for ( int i = 0; i < 10; i++ )
{
n[i] = i + 100;
}
/* output each array element's value */
foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}

}
==================================================
Multidimensional Arrays:
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array. You can declare a 2-dimensional array of strings as:
string [,] names;
or, a 3-dimensional array of int variables as:
int [ , , ] m;
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays.

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns:
Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.
Initializing Two-Dimensional Arrays :
Multidimensional arrays may be initialized by specifying bracketed values for each row. The following array is with 3 rows and each row has 4 columns.
int [,] a = int [3,4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Example:
using System;
namespace ArrayApplication
{
class MyArray
{
114
static void Main(string[] args)
{
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++)
{
for (j = 0; j < 2; j++)
{
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console.ReadKey();
}
}

}
==============================================
Jagged Arrays :
A Jagged array is an array of arrays. You can declare a jagged array named scores of type int as:
int [][] scores;
Declaring an array, does not create the array in memory. To create the above array:
int[][] scores = new int[5][];
for (int i = 0; i < scores.Length; i++)
{
scores[i] = new int[4];

}
You can initialize a jagged array as:

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Example:
The following example illustrates using a jagged array:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
int i, j;
/* output each array element's value */
for (i = 0; i < 5; i++)
{
for (j = 0; j <; 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}

}
===================================================
Passing Arrays as Function Arguments:
You can pass an array as a function argument in C#. The following example demonstrates this:

using System;
namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = (double)sum / size;
return avg;
}
static void Main(string[] args)
{
MyArray app = new MyArray();
/* an int array with 5 elements */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;
/* pass pointer to the array as an argument */
avg = app.getAverage(balance, 5 ) ;
/* output the returned value */
Console.WriteLine( "Average value is: {0} ", avg );
Console.ReadKey();
}
}
}
========================================================
When the above code is compiled and executed, it produces the following result:
Average value is: 214.4

Param Arrays:
At times, while declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times.
The following example demonstrates this:
using System;
namespace ArrayApplication
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{
sum += i;
}
return sum;
}
}
class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = app.AddElements(512, 720, 250, 567, 889);
Console.WriteLine("The sum is: {0}", sum);
Console.ReadKey();
}
}
}
====================================================
When the above code is compiled and executed, it produces the following result:
The sum is: 2938

Methods of the Array Class:
The following table describes some of the most commonly used methods of the Array class: Sr. No, Methods
Clear
Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
2 Copy(Array, Array, Int32)
Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.
121
3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.
GetLength
Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
GetLongLength
Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
GetLowerBound
Gets the lower bound of the specified dimension in the Array.
GetType
Gets the Type of the current instance. (Inherited from Object.)
GetUpperBound
Gets the upper bound of the specified dimension in the Array.
GetValue(Int32)
Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
10 IndexOf(Array, Object)
Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
11 Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.
12 SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
13 Sort(Array)
Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.
14 ToStringk
Returns a string that represents the current object. (Inherited from Object.)

Example
The following program demonstrates use of some of the methods of the Array class:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write("Original Array: ");
foreach (int i in list)
{
Console.Write(i + " ");
}
Console.WriteLine();
// reverse the array
Array.Reverse(temp);
Console.Write("Reversed Array: ");
foreach (int i in temp)
{
Console.Write(i + " ");
}
Console.WriteLine();
//sort the array
Array.Sort(list);
Console.Write("Sorted Array: ");
foreach (int i in list)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
======================================================
Contect me to if you are thinking make a website with low price.
Contect Email : 10julyRAJKUMAR@gmail.com


RAJ KUMAR
( Software Engg)