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
1 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.
2 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.
3 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.
5 public static string Concat( string str0, string str1, string str2, string str3 )
Concatenates four string objects.
6 public bool Contains( string value )
Returns a value indicating whether the specified String object occurs within this string.
7 public static string Copy( string str )
Creates a new String object with the same value as the specified string.
8 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.
9 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.
6 { 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:
1 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.
3 public static bool IsMatch( string input, string pattern )
Indicates whether the specified regular expression finds a match in the specified input string.
4 public MatchCollection Matches( string input )
Searches the specified input string for all occurrences of a regular expression.
5 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.
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
1 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.
2 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.
3 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.
5 public static string Concat( string str0, string str1, string str2, string str3 )
Concatenates four string objects.
6 public bool Contains( string value )
Returns a value indicating whether the specified String object occurs within this string.
7 public static string Copy( string str )
Creates a new String object with the same value as the specified string.
8 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.
9 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.
6 { 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:
1 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.
3 public static bool IsMatch( string input, string pattern )
Indicates whether the specified regular expression finds a match in the specified input string.
4 public MatchCollection Matches( string input )
Searches the specified input string for all occurrences of a regular expression.
5 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.

कोई टिप्पणी नहीं:
एक टिप्पणी भेजें