You are on page 1of 105

Session 2

C# Basics
IMCEITS

 Need of C#
 Goals of C#
 Strengths of C#
 Design of C#
 C# Basics
Need of C#
 Existing languages are powerful.
 Important features are spread out over multiple
languages
 While C++ gives programmers a tremendous amount of
power and control, it may take several more lines of
code to perform an operation requiring a single line of
code in languages like Visual Basic and Java
 C# is the result in the search for a way to marry the
productivity of Visual Basic with the syntax and power
of C++.
Goals of C#
 Give developers a single language with
– A full suite of powerful features
– A consistent and simple syntax
 Increase developer productivity!
– Type safety
– Garbage collection
– Exceptions
– Leverage existing skills
Goals of C# (Cont.)

 Support component-oriented programming


– First class support for component concepts such as
properties, events, attributes
 Provide unified and extensible type system
– Where everything can be treated as an object
 Build foundation for future innovation
– Concise language specification
– Standardization
Strength of C#
A component oriented language
Everything really is an object
Preservation of Investment
Robust and durable software
C# is the first “component oriented” language in the C/C++ family
Component concepts are first class:
Properties, methods, events
Design-time and run-time attributes
Integrated documentation using XML
Enables one-stop programming
No header files, IDL, etc.
Can be embedded in web pages
Traditional views
C++, Java: Primitive types are “magic” and do not
interoperate with objects
Smalltalk, Lisp: Primitive types are objects, but at great
performance cost
C# unifies with no performance cost
Deep simplicity throughout system
Improved extensibility and reusability
New primitive types: Decimal, SQL…
Collections, etc., work for all types
Strength of C# : Preservation of investment
Garbage collection
No memory leaks and stray pointers
Exceptions
Error handling is not an afterthought
Type-safety
No uninitialized variables, unsafe casts
Versioning
Pervasive versioning considerations in all aspects of language
design
Strength of C# : Robust and durable software
C++ heritage
Namespaces, enums, unsigned types, pointers (in unsafe
code), etc.
No unnecessary sacrifices
Interoperability
What software is increasingly about MS C#
implementation talks to XML, SOAP, COM, DLLs, and
any .NET language
Millions of lines of C# code in .NET
Short learning curve
Increased productivity
Design of C#
 Derived from the features and syntaxes of other
languages
– The safety of Java
– The ease of Visual Basic
– The power of C++
 Uses the .NET Framework
 Plus several unique features
C# Basics

 Program Structure  Flow Control in C#


 Keywords  Type Conversion and
 Data Types Casting
 Literals  Boxing & Unboxing
 Comments value types
 Variables  Arrays
 Constants  Strings
 Operators
Sample Program
using System;
using System.Data;

namespace <project name>


{
<modifier > class <class name>
{
static void Main()
{
[statements]
}
}
}
Program Structure
using System;  uses the namespace System
 entry point must be called Main
 output goes to the console
namespace Wrox.ProCSharp.Basics  file name and class name need
{ not be identical
class MyFirstCSharpClass
{
static void Main()
{
Console.WriteLine("This isn't at all like Java!");
Console.ReadLine();
}
}
}
Declaration Space
The program area to which a declaration belongs
Entities can be declared in a ...
-namespace: Declaration of classes, interfaces, structs, enums,
delegates
-class, interface, struct: Declaration of fields, methods, properties,
events, indexers, ...
-enum: Declaration of enumeration constants
-block: Declaration of local variables
Declaration Space (Cont.)
Scoping rules
-A name must not be declared twice in the same declaration space.
-Declarations may occur in arbitrary order.
Exception: local variables must be declared before they are used
Visibility rules
-A name is only visible within its declaration space
(local variables are only visible after their point of declaration).
-The visibility can be restricted by modifiers (private, protected, ...)
Namespaces
File:X.cs File:Y.cs

Equally named namespaces in different files constitute a single


declaration space.
Nested namespaces constitute a declaration space on their own.
Namespaces (Cont.)
File:Color.cs File:Figure.cs File:Triangle.cs

using Util.Figures;
class Test {
Rect r; // without qualification (because of using Util.Figures)
Triangle t;
Util.Color c; // with qualification
}
 Foreignnamespaces
 must either be imported (e.g. using Util;)
 or specified in a qualified name (e.g. Util.Color)
Most programs need the namespace System => using System;
Namespaces (Cont.)

 If no namespace is specified => anonymous default


namespace
 Namespaces may also contain structs, interfaces, delegates
and enums
 Namespace may be "reopened" in other files
 Simplest case: single class, single file, default namespace
Block

 The declaration space of a block includes the declaration spaces of


nested blocks
 Formal parameters belong to the declaration space of the method
block
 The loop variable in a for statement belongs to the block of the for
statement
 The declaration of a local variable must precede its use.
Case-sensitive
White space means nothing
Semicolons (;) to terminate statements
Code blocks use curly braces ({})
C++/Java style comments
// or /* */
Also adds /// for automatic XML documentation
C# Keywords

 Essential part of language definition


 Implement specific features of the language
 Cannot be used as identifiers except when they are
prefixed with the ‘@’ character.
Data Types
 All types ultimately inherit from object
- Compatible with object
- Classes, enums, arrays, delegates, structs, …
 An implicit conversion exists from any type to type
object
- can be assigned to variables of type object
- all operations of type object are applicable to them
 15 predefined types
- 13 value types
- 2 reference types (string and object)
Data Types (Cont.)
Value Types

 Fixed length
 Store on the stack
 When a value of a variable is assigned to another
variable, the value is actually copied (i.e two identical
copies of the value are available in memory)
Value Types (Cont.)

 Predefined value types and Userdefined value types


 Predefined value types : numeric types, boolean types
and character types
 Userdefined value types : struct and enumerations
 A new type : nullable type
- this type variable can hold an undefined value
- any value type variable can be defined as a nullable
type
Reference Types
 Variable length
 Store on the heap
 When an assignment between two reference variables
occurs, only the reference is copied
 The actual value remains in the same memory location
(i.e there are two references to a single value)
Reference Types (Cont.)
 Two groups : user-defined and predefined
 User-defined ( or complex ) types
- Classes, Interfaces, Delegates and Arrays
 Predefined ( or simple ) types
- Object type and String type
Literals
 Value constants assigned to variables or results of
expressions

 Numeric Literals - Integer Literals, Real Literals


 Boolean Literals
 Character Literals - Single character Literals, String
Literals, backslash character literal
Integer Literals

 Integers – decimal and hexadecimal


 In hexadecimal, 0x or 0X is preceded.
 0x2, 0X9F, 0Xbcd, 0x1b

Example:
int hex = 0x9f;
Console.WriteLine("{0:x}",hex);
Real Literals

 Exponential or scientific notation


 Mantissa e exponent
 215.65 (2.1565e2)
 0.65e4 12e-2 3.18E3

Example:
double exp = 3.18e3;
Console.WriteLine("{0:e}", exp);
Boolean Literals

 2 values
 true and false

Example:
bool flag = false;
Console.WriteLine(flag);
Single Character Literals & String Literals

 ‘2’ ( Single character literals )


 “2000019” ( String literals )

Example:
char grade=‘A’;
string result=“Credit”;
Backslash Character Literals
 \a - Alert (usually the HW beep)
 \b - Backspace
 \n - New line
 \0 - Null
 \t - Horizontal tab
 \v - Vertical tab
 \' - Single quote
 \" - Double quote
 \\ - Backslash
 \f - Form feed
 \r - Carriage return
Comments

 Single-line comments - //
 Multiline comments - /* */
Variables
 Declaration
datatype identifier;
int i;
 Initialization of Variables
- two methods
- if not initialized explicitly, variables are by default
zeroed out when they are created (for variables are fields
in a class or struct )
- Must be explicitly initialized (for local variables in a
method)
 Variable scope
- region of code from which the variable can be accessed
- field , local variable in method, local variable in block
Default Values
 A variable is either explicitly assigned a value or
automatically assigned a default value
Type Default Value
All integer types 0

char type ‘\x000’


float type 0.0f
double type 0.0d
decimal type 0.0m
bool type false
enum type 0
All reference types null
Constants
 Declaration
const int a = 100;
 Must be initialized when a constant variable is declared
 Once a value has been assigned
 It can never be overwritten
 Value of constant must be computable at compile time
 Always implicitly static (don’t have to include static
modifier)
Operators
Operators
Category Operator Category Operator
Arithmetic + Comparison ==
- !=
* <
/ >
% >=
Logical & <=
| Assignment =
^ +=
~ -=
&& *=
|| /=
! %=
String concatenation + |=
^=
Increment and decrement ++ <<=
-- >>=
Bit shifting << Member access (for objects .
>> and structs)
Operators (Cont.)
Category Operator Category Operator
Indexing (for arrays and [] Indirection and address *
indexers) ->
Case () & (unsafe
code only)
Conditional (the Ternary ?: []
Operator)
Namespace alias qualifier ::
Delegate concatenation and +
removal - Null coalescing operator ??

Object creation new


Type information sizeof (unsafe code
only)
is
typeof
as
Overflow exception control checked
unchecked
Flow Control in C#
 Loop Statements
- while
- do-while
- for
- foreach
 Jump Statements
- break
- continue
- goto
- return
 Selection Statements
- if - else
- switch - default
while
syntax:
while (condition) statement[s]

 Pre-test loop
bool condition =false;
int i=3;
while(!condition)
  {
System.Console.WriteLine(“{0}\t”,i);
i--;
if (i==0) condition=true;
}
do-while
syntax:
do{
Statements;
} while (condition)
 post-test version of while loop
bool condition =false;
int i=3;
do
  {
System.Console.WriteLine(“{0}\t”,i);
i--;
if (i==0) condition=true;
} while(!condition);
for
syntax:
for (initializer;condition;iterator)
statement[s]

 Pre-test loop
 Loop condition is evaluated before the loop statements are
executed
for (int i=0;i<5;i++)
  System.Console.WriteLine(i);
foreach
syntax:
foreach (variable1 in variable2) statement[s]
 Iterates through all items in an array or collection
 collection is a class which implements the interface
IEnumerable or declares GetEnumerator
 To iterate through the values contained by any object which
implements the IEnumerable interface
 When a 'foreach' loop runs, the given variable1 is set in turn to
each value exposed by the object named by variable2.
int[] a = new int[]{1,2,3};
foreach (int b in a)
  System.Console.WriteLine(b);
break
 breaks out of the 'while' and 'for' loops and the
'switch' statements

int a = 0;
while (true)
{
     System.Console.WriteLine(a);
     a++;
     if (a == 5)
         break;
}
continue
 Can be placed in any loop structure
 When it executes, it moves the program counter
immediately to the next iteration of the loop

int y = 0;
for (int x=1; x<101; x++)
{
     if ((x % 7) == 0)
         continue;
     y++;
}
goto
 Is used to make a jump to a particular labelled part of the
program code and in the 'switch' statement
To construct a loop (this usage is not recommended)

int a = 0;
start:
System.Console.WriteLine(a);
a++;
if (a < 5)
     goto start;
return
 A method will stop and return a value if it reaches a
'return' statement at any point in its execution
 The type returned is given at the end of such a return
statement
 Its type must correspond with that specified in the
method declaration

public static int exampleMethod()


{
    int i =0;
return i;
}
Selection Statements
 if (condition) [statements]

 if (condition)
[statements]

else if (condition)
[statements]

else [statements]
Switch Expression
 Type of switch expression switch ( expression )
{
case value-1:
- numeric, char, enum or
block-1
string break;
(null ok as a case label). case value-2:
block-2
 No fall-through! break;
- Every statement sequence ……………..
default :
in a case must be terminated
default-block
with break (or return, goto, break;
throw) }
Boxing and Unboxing

 Boxing is the conversion of a value type on the


stack to object type on the heap.
 Unboxing is the conversion from an object type
back to a value type.
Boxing and Unboxing (Cont.)

 Conversion between value type and reference type


packet p = new packet();
object o = (object)p; // boxed
packet p2 = (packet)o; // unboxed
Boxing : Example
Implicit Conversion Explicit Conversion

int m=100; int m=100;


// creates a box to hold m // creates a box to hold m
Object om=m; Object om=(object)m;
// m is on the stack
// om resides on the heap
Unboxing : Example

Explicit Conversion

int m=100;
Object om=m;
int n= (int) om;
Arrays

 One-dimensional Arrays
 Multidimensional Arrays
 Jagged Arrays
Arrays
 All arrays are instances of the base class System.Array
 Many useful properties and methods
Rank, Length, Sort, Clear, Clone, GetLength,
IndexOf
 The overhead is greater than that for C++ arrays
 IndexOutOfRangeException
 Copying an array variable copies the reference only
 Implement ICloneable, IList, ICollection, IEnumerable
 One-dimensional Arrays
 Multidimensional Arrays
One- Dimensional Arrays

int[] a = new int[3]; // initialze to default zero


int[] b = new int[] {3, 4, 5};
int[] c = {3, 4, 5};
SomeClass[] d = new SomeClass[10];// Array of references
SomeStruct[] e = new SomeStruct[10];// Array of values
//(directly in the array)
int len = a.Length; // number of elements in a
Multidimensional arrays
Rectangular

int[,] a = new int[2, 3];


int x = a[0, 1];
// to display no. of elements
int len = a.Length; // 6
// to display no. of rows
len = a.GetLength(0); // 2
// to display no. of columns
len = a.GetLength(1); // 3
Jagged- array of arrays
type [][] array_name=new type[size][];

int[][] a = new int[2][];


a[0] = new int[3];
a[1] = new int[4];
int x = a[0][1];
// to display no. of rows
int len = a.Length;// 2
len = a[0].Length;// 3
Multidimensional arrays
3D array
type [ ,…,] array_name=new type[size1,size2,…,sizeN];

int[2,3,4] array = new int[2,3,4];


int n=0;
for (int i=0;i<2;i++)
for(int j=0;j<3;j++)
for (int k=0;k<4;k++)
array[I,j,k]= n++;
Copying Array

int[] intArray1 = {1, 2};


int[] intArray2 = (int[])intArray1.Clone();

Person[] beatles = {
new Person { FirstName="John", LastName="Lennon" },
new Person { FirstName="Paul", LastName="McCartney" }
};
Person[] beatlesClone = (Person[])beatles.Clone();
Sorting Array

string[] names = {
"Christina Aguilera",
"Shakira",
"Beyonce",
"Lady Gaga"
};
Array.Sort(names);

// Array.Sort () can be used only .net framework 4.5 and above


version
ArraySegment <T>

static int SumOfSegments(ArraySegment<int>[] segments)


{
int sum = 0;
foreach (var segment in segments)
{
for (int i = segment.Offset; i < segment.Offset +
segment.Count; i++)
{
sum += segment.Array[i];
}
}
return sum;
}
Strings
 Stirngs Class
 Constructing Strings
 Operating on Strings
 Arrays of Strings
 Strings & switch statements
 Formatting Strings
 System.Strings
 StringBuilder Members
 Introduction to Regular Expression
the string type is immutable, i.e.,
once it has been created, a string cannot be changed
No characters can be added or removed from it, nor can its
length be changed
a string's contents have been changed, what has really happened is
that a new string instance has been created.
cannot be edited but it can be assigned.
has eight constructors
string st=new string(‘a’,5); //aaaaa
string st=new string(new char[5]{‘h’,’e’,’l’,’l’,’o’})
char[] mychararray = new char[11]{'N','e','w','Y','o','r','k','C','i','t','y'};
// NewYorkCity
string mystring = new string(mychararray,3,6);
//YorkCi
Constructing Strings
 A predefined reference type

 Declaration

string st1;
String st2;

"string" is a keyword and can't be used "string" as an


identifier. Alias System.String class.
"String" is not a keyword, and can be used it as an
identifier:
Constructing Strings (Cont.)
 Initializing string

string st1=“IMCEITS”;
String st2=“UCSY”

 Assigning String Literals

string st1;
st1= “DAST”
String st2;
st2=“MOST”;
Constructing Strings (Cont.)
 Verbatim Strings - Verbatim string literals begin with @"
and end with the matching quote. They do not have escape
sequences.
 create variables named
@if, @string
string st1=@“\EBG\CSharp\my.cs”;
or
string st1=“\\EBG\\CSharp\\my.cs”;
 a single string to span more than one line
string str =
@"I'm so happy to be a string
that is split across
a number of different
lines.";
Constructing Strings (Cont.)
 string st1=@“\EBG\CSharp\my.cs”;
or
string st1=“\\EBG\\CSharp\\my.cs”;

 Assigning String Literals

string st1;
st1= “DAST”
String st2;
st2=“MOST”;
public sealed class String
public char this[int index] {get;}
public int Length {get;}
public static int Compare(string strA, string strB); // Culture!
public static int CompareOrdinal(string strA, string strB); // without Culture!
public static string Format(string format, object arg0);
public int IndexOf(string);
public int IndexOfAny(char[] anyOf);
public int LastIndexOf(string value);
public string PadLeft(int width, char c); // s.PadLeft(10,'.');  ".....Hello"
public string[] Split(params char[] separator);
public string Substring(int startIndex, int length);
...
}
Operations on Strings

 Copying Strings
 Concatenating Strings
 Inserting Strings
 Searching Strings
 Comparing Strings
 Finding Substrings
Copying Strings

 Create new copies of existing strings


 overloaded = operator
 static Copy method
string st1=“ This is language school”;
string st2;
st2=st1;
st3= string.Copy(st1);
Concatenating Strings

 Create new strings by concatenating existing strings.


 overloaded + operator
 static Concat method
string st1=“IMCEITS”, st2=“, UCSY”;
string st3=st1+st2;
string st4= stirng.Concat (st1,st2);
Inserting Strings

 Returns a new string with a substring inserted at a


specified locations
string st1=“IMITS”;
string st2=st1.Insert(2,”CE”);
string st3= st2.Insert(7,”,Training School”);
Comparing Strings
using System;
class MainClass
{
 public static void Main()
  {   
    int result;
    result = String.Compare("bbc", "abc");
    Console.WriteLine("String.Compare(\"bbc\", \"abc\") = " + result);
    result = String.Compare("abc", "bbc");
    Console.WriteLine("String.Compare(\"abc\", \"bbc\") = " + result);
    result = String.Compare("bbc", "bbc");
    Console.WriteLine("String.Compare(\"bbc\", \"bbc\") = " + result

   Output
String.Compare("bbc", "abc") =1
String.Compare(“abc", “bbc") =-1
String.Compare("bbc", “bbc") =0
Comparing Strings
    result = String.Compare("bbc", "BBC", true);
    Console.WriteLine("String.Compare(\"bbc\", \"BBC\", true) = " + result);
    result = String.Compare("bbc", "BBC", false);
    Console.WriteLine("String.Compare(\"bbc\", \"BBC\", false) = " + result);
    result = String.Compare("Hello World", 6, "Goodbye World", 8, 5);
    Console.WriteLine("String.Compare(\"Hello World\", 6, " + "\"Goodbye 
World\", 8, 5) = " + result); // space compare
 }
}

   Output
String.Compare("bbc", "BBC", true) =0
String.Compare("bbc", "BBC", false) =-1
String.Compare("Hello World", 6, " + "Goodbye World", 8, 5)  =0
Split Strings
using System;

class String_Split
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
string myString9 = String.Join(".", myStrings);
Console.WriteLine("After join is " + myString9);
myStrings = myString9.Split('.');
foreach (string mySplitString in myStrings)
{
Console.WriteLine("mySplitString = " + mySplitString);
}
}
}
Split Strings

   Output

After join is To.be.not.to.be


mySplitStirng = To
mySplitStirng = be
mySplitStirng = not
mySplitStirng = to
mySplitStirng = be
Finding Strings
using System;

class Finding_string
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
foreach (string st in myStrings)
{
bool flag = st.StartsWith("b");
Console.WriteLine(flag.ToString());    Output
} False
}
} True
False
False
False
True
Remove, Replace,
using System;
class String_Remove
{
public static void Main()
{
string[] myStrings = {"To", "be", "or", "not", "to", "be"};
string myString = String.Join(".", myStrings);   
string myString10 = myString.Insert(6, "A, ");
Console.WriteLine("myString.Insert(6, \"A, \") = " + myString10);
string myString11 = myString10.Remove(14, 7);
Console.WriteLine("myString10.Remove(14, 7) = " + myString11);
string myString12 = myString11.Replace(',', '?');
Console.WriteLine("myString11.Replace(',', '?') = " + myString12);
string myString13 = myString12.Replace("to be", "Or not to be A");
Console.WriteLine("myString12.Replace(\"to be\", \"Or not to be A\") 
= " + myString13);
}
}
Remove, Replace,

   Output

myString.Insert(6,”A, “)= To.be.A, or.not.to.be


mySting10.Remove(14,7) = To.be.A, or.no
myStirng11.Replace(‘,’, ‘?’) = To.be.A? or.no
mySting12.Replace(“to be”,”Or not to be A”)= To.be.A? or no
Arrays of Strings
 Declaration
string [] str=new string[3];

 Initialization
string [] str= {“This”,”is”,”a”,”test”};
Strings & switch statements
 Strings can be used in switch statements
foreach(string s in strs)
{ switch(s)
{ case “Mon” : num=1;break;
case “Tue” : num=2;break;
case “Wed” : num=3;break;
}
}
Formatting String
 String.Format (format string , arguments)
 Format string contains groups of the form
{ index[ , alignment][ : codes]}

 Relies extensively on objects’ ToString() method


 For numbers
n - use comas to separate thousand
e - scientific notation
 x and X - hexadecimal
0 - padding with 0s
# - position of digits
Formatting String (Cont.)
 d and D - dates and times , short/ long date
 t/T - short / long time
 mm - minutes
 MM - month as number
 MMM - month as 3 letter code
 MMMM - month name
Formatting String (Cont.)
float num = 40030F;
Console.WriteLine("Scientific notation is {0,10:E}", num);
Console.WriteLine("Locale notation is {0,10:C}", num);
int num1 = 7000;
Console.WriteLine("General integer notation is {0,10:D}", num1);
Console.WriteLine("Hexadecimal notation is {0,10:X}", num1);
   Output

Scientific notation is 4.003000E+004


Locale notation is $40,030.00
General integer notation is 7000
Hexadecimal notation is 1B58
Formatting String (Cont.)
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

Console.WriteLine (String.Format("{0:y yy yyy yyyy}", dt));


Output : 8 08 008 2008 //year
Console.WriteLine (String.Format("{0:M MM MMM MMMM}", dt));
Output : 3 03 Mar March //month
Console.WriteLine (String.Format("{0:d dd ddd dddd}", dt));
Output : 9 09 Sun Sunday //day
Console.WriteLine (String.Format("{0:h hh H HH}", dt));
Output: 4 04 16 16 //hour 12/24
Console.WriteLine (String.Format("{0:m mm}", dt));
Output: 5 05 //minute
Console.WriteLine (String.Format("{0:s ss}", dt));
Output : 7 07 //second
Strings are immutable objects
Stringbuilders are mutable or dynamically changeable without creating
new object.
System.Text.StringBuilder
The String Builder class is designed for situations when one needs to work
with a single string and make an arbitrary number of iterative changes to it.
Many StringBuilder class methods are the same as those of the String class.
The string content of a StringBuilder class can be changed without the
necessity of allocating additional memory.
public sealed class StringBuilder {
public int Capacity {get; set;}
public int Length {get; set;}
StringBuilder Append(...);
StringBuilder AppendFormat(...);
StringBuilder Insert(int index, ...);
StringBuilder Remove(int startIndex, int length);
StringBuilder Replace(char oldChar, char newChar);
string ToString();
}
StringBuilder myBuilder = new StringBuilder("Hello World 123456");
Console.WriteLine(myBuilder.Capacity);
myBuilder.Capacity = 30;
Console.WriteLine(myBuilder.Length);
myBuilder.Append(“ Again “);
Console.WriteLine(myBuilder.Capacity);    Output
Console.WriteLine(myBuilder.Length); 32
18
30
25
Regular Expression (Cont.)
 System.Text.RegularExpressions
 Regular expression (regex) is a compact way of
representing a certain type of pattern
 For most patterns, multiple equivalent regrexs exist
 Fundamental operation : regex matching – deciding if a
given input string can be mapped to the pattern
 Many applications
 Used by compiler as a first step of program analysis
 Various popular Unix commands such as grep
 In web programming mostly for validating user input
Regular Expression (Cont.)
 Two features
 A set of escape codes for identifying specific types of
characters ( any one character, a word break, one optional
character and so on)
 A system for grouping parts of substrings and intermediate
results during a search program.
Regular Expression
Symbol Meaning Example Matches
^ Beginning of input text ^B B, but only if first character in text
$ End of input text X$ X, but only if last character in text
. Any single character except the i.ation isation, ization
newline character (\n)
* Preceding character may be ra*t rt, rat, raat, raat, and so on
repeated 0 or more times
+ Preceding character my be ra+t rat, raat, raaat and so on (but not rt)
repeated 1 or more items
? Preceding character may be ra?t rt and rat only
repeated 0 or 1 times
\s Any whitespace character \sa [space]a, \ta,\na
\b Word boundary Ion\b Any word ending in ion
\B Any position that isn’t a word \BX\B Any X in the middle of a word
boundary
Regular Expression: Example 1
string str;
str = "Amar, Akbar, Antony are friends!";
Regex reg = new Regex(" |,");
StringBuilder sb = new StringBuilder();
int count = 1;
foreach (string sub in reg.Split(str))
{
sb.AppendFormat("{0}: {1}\n", count++, sub);
}
Console.WriteLine(sb);

   Output
1: Amar
2: Akbar
3: Antony are friends
Regular Expressions : Example 2
using System;
using System.Text.RegularExpressions;
namespace Session2
{ class TestRegularExpressions
{ static void Main()
{ string[] sentences = { "cow over the moon", "Betsy the Cow", "cowering
in
the corner", "no match here“ };
string sPattern = "cow“;
foreach (string s in sentences)
{ System.Console.Write("{0,24}", s);
if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern,
RegexOptions.IgnoreCase))
{System.Console.WriteLine(" (match for '{0}' found)", sPattern); }
else
{ System.Console.WriteLine(); }
}
Regular Expressions : Example 2(cont.)

   Output

cow over the moon < match for ‘cow’ found>


Besty the Cow <match for ‘cow’ found>
covering in the corner <match for ‘cow’ found>
no match here
Regular Expressions : Example 3
using System;
using System.Text.RegularExpressions;
public class Example {
public static void Main() {
string[] partNumbers= { "1298-673-4192", "A08Z-931-468A", "_A90-
123-129X", "12345-KKA-1230", "0919-2893-1256" };
Regex rgx = new Regex(@"^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}
[A-Za-z0-9]$");
foreach (string partNumber in partNumbers) Console.WriteLine("{0}
{1} a valid part number.", partNumber, rgx.IsMatch(partNumber) ? "is"
: "is not"); } }
The example displays the following output: 

1298-673-4192 is a valid part number. 


A08Z-931-468A is a valid part number. 
_A90-123-129X is not a valid part number. 
12345-KKA-1230 is not a valid part number. 
0919-2893-1256 is not a valid part number.
The regular expression pattern :
^[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]$
Pattern Description
^ Begin the match at the beginning of the line.

[a-zA-Z0-9] Match a single alphabetic character (a through z or A through Z) or


numeric character.
\d{2} Match two numeric characters.
[a-zA-Z0-9] Match a single alphabetic character (a through z or A through Z) or
numeric character.
- Match a hyphen.
\d{3} Match exactly three numeric characters.
(-\d{3}){2} Find a hyphen followed by three numeric characters, and match two
occurrences of this pattern.
[a-zA-Z0-9] Match a single alphabetic character (a through z or A through Z) or
numeric character.
$ End the match at the end of the line.

You might also like