C Advanced Features and Programming Techniques Step by Step C Book 250208 102015
C Advanced Features and Programming Techniques Step by Step C Book 250208 102015
Nathan Clark
© Copyright 2018 by Nathan Clark - All rights reserved.
Introduction
1. Interfaces in C#
2. Namespaces
3. File I/O Operations
4. Exception Handling
5. Attributes
6. Properties
7. Delegates
8. Reflection
9. Collections
10. Generics
11. Events
12. Multithreading
13. Regular Expressions
Conclusion
About the Author
Introduction
stud1.StudentID = 1;
stud1.StudentName = "John";
stud1.marks1 = 10;
stud1.marks2 = 20;
stud1.DisplayMarks();
Console.WriteLine("The Total marks is " + stud1.Calculate());
Console.Read();
}
}
}
We can also have a class inherit multiple interfaces at once. Let’s look at
an example of this.
Example 2: The following program is used to show how classes can use
multiple interfaces.
using System;
namespace Demo
{
// Defining the interface
public interface Marks
{
// Declaring the interface methods
void DisplayMarks();
int Calculate();
}
class Program
{
// The main function
static void Main(string[] args)
{
stud1.StudentID = 1;
stud1.StudentName = "John";
stud1.marks1 = 10;
stud1.marks2 = 20;
stud1.DisplayMarks();
Console.WriteLine("The Total marks is " + stud1.Calculate());
stud1.InputCity("New York");
stud1.DisplayCity();
Console.Read();
}
}
}
If both the get and set methods are defined, it means that the property is a
read-write property. Let’s now look at an example of how properties in
interfaces work.
stud1.StudentID = 1;
stud1.StudentName = "John";
stud1.marks = 10;
stud1.Subject = "Subject1";
Console.Read();
}
}
}
Namespaces are used to logically separate functions that have the same
name. So we could have two functions with the same name and same
parameters, but with different functionality. Without the need to define
classes, we can just segregate them into namespaces.
The syntax of a namespace is shown below.
namespace namespaceName
{
Class definition
{
// Define the functions
}
}
Which results in using the functions that are defined in the ‘System’
namespace.
// One namespace
namespace NameA{
public class ClassA
{
public void FunctionA(){
Console.WriteLine("This is namespace A");
}
}
}
// Second namespace
namespace NameB{
public class ClassB
{
public void FunctionA()
{
Console.WriteLine("This is namespace B");
}
}
}
namespace Demo
{
class Program
{
Console.Read();
}
}
}
We can also utilize the ‘using’ directive to use functions without the need
to specify the namespace when calling the function. Let’s look at an
example of the using clause.
// One namespace
namespace NameA{
public class ClassA
{
public void FunctionA(){
Console.WriteLine("This is namespace A");
}
}
}
// Second namespace
namespace NameB{
public class ClassB
{
public void FunctionA()
{
Console.WriteLine("This is namespace B");
}
}
}
namespace Demo
{
class Program
{
Console.Read();
}
}
}
Example 6: The following program is used to show the way to use nested
namespaces.
using System;
// One namespace
namespace NameA{
public class ClassA
{
public void FunctionA(){
Console.WriteLine("This is namespace A");
}
}
// inner namespace
namespace NameB
{
public class ClassB
{
public void FunctionA()
{
Console.WriteLine("This is namespace B");
}
}
}
}
namespace Demo
{
class Program
{
Console.Read();
}
}
}
namespace Demo
{
class Program
{
With this program, the output is as shown below. The output will however
vary from system to system.
Drive C:\
Drive type:Fixed
Drive D:\
Drive type:Fixed
3.2 DirectoryInfo
This class can provide more information pertaining to a particular
directory.
namespace Demo
{
class Program
{
Console.Read();
}
}
}
With this program, the output is as shown below. Again, the output will
vary from system to system.
Does the directory exist True
The creation time of the directory is 04/28/2017 11:12
3.3 FileInfo
This class can provide more information pertaining to a particular file.
Example 9: The program below showcases the way to use the FileInfo
class.
using System;
using System.IO;
namespace Demo
{
class Program
{
Console.Read();
}
}
}
With this program the output is as shown below, and will vary from
system to system.
Does the directory exist True
The creation time of the directory is 04/28/2017 11:12
The size of the file is 73
3.4 FileStream
This class can be used to read the contents of a file or write contents to a
file. Note that this class works with the file in bytes. The general syntax
when creating a new object of this class is given below.
FileStream fileobj = new FileStream("nameoffile",Options)
Where the options can be any one, or a combination of, the following:
Append - It opens an existing file and puts the cursor at the end of
file. It will alternatively create the file, if the file does not exist.
Create - It creates a new file.
CreateNew - It specifies to the operating system, that it should create
a new file.
Open - It opens an existing file.
OpenOrCreate - It tells the operating system to open a file if it
exists, otherwise it creates a new file.
Truncate - It opens an existing file and truncates its size to zero
bytes.
The steps for reading contents from a file using the FileReader class is
shown below:
First use the FileStream class to open the file with one of the
abovementioned options.
When you read from the file, you will get an array of bytes. Hence
this should be stored in a byte array.
The byte array then needs to be converted to a string and then
displayed in the console.
Let’s look at an example of how to use the Filereader class.
Example 10: The next program is used to showcase the way to use the
FileStream class.
using System;
using System.IO;
namespace Demo
{
class Program
{
src.Read(bytes, i, numBytes);
Console.Read();
}
}
}
Let’s now look at an example of how to use the FileStream class to write
the contents to a file.
Example 11: The following program shows how to use the FileStream
class to write contents to a file.
using System;
using System.IO;
namespace Demo
{
class Program
{
src.Write(bytes,0,str.Length);
Console.Read();
}
}
}
With this code, we just need to specify the name of the file. Once the file
has been opened using the StreamReader class, we can use the built-in
functions, such as ReadLine, to read the contents of the file line by line.
Let’s look at an example of how to use the StreamReader class.
Example 12: The program below showcases the way to use the
StreamReader class.
using System;
using System.IO;
namespace Demo
{
class Program
{
With this program, the output is as shown below. The output will vary
depending on the contents of the source file.
Hello World
If we have many lines in the file, we can use the ReadtoEnd function to
read all the contents of the file as shown in the example below.
Example 13: This program shows how to use the StreamReader class
with the ReadtoEnd function.
using System;
using System.IO;
namespace Demo
{
class Program
{
With this program, the output is as below. The output will again vary
depending on the contents of the source file.
Hello World
Hello World Again
3.6 StreamWriter
This class can be used to write contents to a stream, such as a file. The
general syntax when creating a new object of this class is given below.
StreamWriter fileobj = new StreamWriter("nameoffile")
With this code, we only need to specify the name of the file. Once the file
has been opened using the StreamWriter class, we can use the built-in
functions, such as Write and WriteLine, to write the contents to the file.
Let’s look at an example of how to use the StreamReader class.
Example 14: The program below is used to show the way to use the
StreamWriter class.
using System;
using System.IO;
namespace Demo
{
class Program
{
Now if we open the “newHello.html” file, we will have the string ‘Hello
World’ in the file.
We can also ensure that whenever content is written to a file, it is
appended to the end of the file. All we need to do is to add the keyword of
‘true’ when opening the file using the StreamWriter.
The example below shows how this can be done.
Example 15: The following program shows how to use the StreamWriter
class to append data.
using System;
using System.IO;
namespace Demo
{
class Program
{
Example 16: The next program shows the way to use the StringReader
class.
using System;
using System.IO;
namespace Demo
{
class Program
{
We can also use the StringReader class to read all the contents of a string
using the ReadtoEnd function as shown below.
Example 17: The program below shows how to use the StringReader
class with the ReadtoEnd function.
using System;
using System.IO;
namespace Demo
{
class Program
{
Example 18: This program showcases the way to use the StringWriter
class.
using System;
using System.IO;
namespace Demo
{
class Program
{
strWriter.WriteLine("Hello");
strWriter.WriteLine("World");
strWriter.WriteLine("Again");
Now let’s look at a simple example of using the try catch block.
Example 19: The following program is used to showcase the way to use
the exception handling blocks.
using System;
using System.IO;
namespace Demo
{
class Program
{
Table 2: Exceptions
Exception Description
System.IO.IOException This is used to handle I/O
errors
System.IndexOutOfRangeException This is used to handle
errors generated when a
method refers to an array
index out of range
System.ArrayTypeMismatchException This is used to handle
errors generated when the
type is mismatched with
the array type
System.NullReferenceException This is used to handle
errors generated from
referencing a null object
System.DivideByZeroException This is used to handle
errors generated from
dividing a dividend with
zero
System.InvalidCastException This is used to handle
errors generated during
typecasting
System.OutOfMemoryException This is used to handle
errors generated from
insufficient free memory
System.StackOverflowException This is used to handle
errors generated from
stack overflow
This means we could have written our earlier program in the following
way.
Example 20: The following program shows how to use the built-in
exceptions.
using System;
using System.IO;
namespace Demo
{
class Program
{
Example 21: The program below showcases the way to use multiple
catch blocks.
using System;
using System.IO;
namespace Demo
{
class Program
{
//constructor
}
Example 22: The following program is used to show the way to use
attributes in C#.
using System;
using System.IO;
namespace Demo
{
[AttributeUsage(AttributeTargets.All)]
public class TypeAttribute : System.Attribute
{
public readonly string Type;
public string Subject // Topic is a named parameter
{
get
{
return Subject;
}
set
{
Subject = value;
}
}
void Display()
{
Console.WriteLine("The ID of the student is " + ID);
Console.WriteLine("The Name of the student is " + name);
}
}
class Program
{
// The main function
static void Main(string[] args)
}
}
Now let’s look at another example on the usage of an attribute. This time
around, we are going to do two things. First we are going to use
constructors to provide a value to a custom attribute, and then we are
going to get the value of the custom attribute.
namespace Demo
{
public class CustomAttribute : Attribute
{
// Private fields.
private string name;
[Custom("John")]
class Person
{
public int ID;
public string name;
void Display()
{
Console.WriteLine("The ID of the student is " + ID);
Console.WriteLine("The Name of the student is " + name);
}
}
class Program
{
static void Main(string[] args)
{
Type t = typeof(Person);
CustomAttribute MyAttribute =
(CustomAttribute)Attribute.GetCustomAttribute(t,
typeof(CustomAttribute));
if (MyAttribute == null)
{
Console.WriteLine("The attribute was not found.");
}
else
{
// Get the Name value.
Console.WriteLine("The Name Attribute is " +
MyAttribute.Name);
}
Console.ReadKey();
}
}
}
Properties are members of a class that can be accessed using ‘getter’ and
‘setter’ methods. This is normally used to get and set the values of private
members of a class.
The syntax for defining a property is shown below.
public datatype propertyname
{
get
{
return propertyname;
}
set
{
propertyname = value;
}
}
Where:
‘datatype’ is the type of data associated with the property.
‘propertyname’ is the name of the property.
The ‘get’ and ‘set’ methods are used to get and set the value of the
property.
Before we jump into an example on properties, let’s look at a classic
example of how we would get and set fields of a typical class.
Example 24: The program below shows how to use fields in a class.
using System;
using System.IO;
namespace Demo
{
class Student
{
private int ID;
private string name;
class Program
{
// The main function
static void Main(string[] args)
{
Student stud1 = new Student();
stud1.Input(1, "John");
stud1.Display();
Console.Read();
}
}
}
namespace Demo
{
class Student
{
// Defining the members
private int id;
private string name;
This class has plain get and set methods, with the properties defined as
‘abstract’. Next, in order to ensure that the derived class uses these
properties, we need to mention the ‘override’ keyword with the property.
class Student : Person
{
// Defining the members
private int id;
private string name;
Example 26: The following program shows the way to use properties in
an abstract class.
using System;
using System.IO;
namespace Demo
{
public abstract class Person
{
public abstract int ID
{
get;
set;
}
public abstract string Name
{
get;
set;
}
}
class Student : Person
{
// Defining the members
private int id;
private string name;
// Defining the properties
public override int ID
{
get
{
return id;
}
set
{
id = value;
}
}
class Program
{
// The main function
static void Main(string[] args)
{
Example 27: The program below showcases how to use read only
properties.
using System;
using System.IO;
namespace Demo
{
class Student
{
// Defining the members
private int id;
private string name;
private int subjectID = 1;
class Program
{
// The main function
static void Main(string[] args)
{
Since we are defining the ‘SubjectID’ property with only the ‘getter’
property, we cannot set the value of the property.
With this program, the output is as follows:
The ID of the student is 1
The Name of the student is John
The SubjectID is 1
7. Delegates
Example 28: The following program is used to showcase the way to use
a delegate.
using System;
using System.IO;
namespace Demo
{
class Program
{
// This is the method which will be pointed to by the delegate
function
public static void Display()
{
Console.WriteLine("Hello world");
}
Example 29: The next program shows how to use a delegate with
multiple methods.
using System;
using System.IO;
namespace Demo
{
class Program
{
// This is the method which will be pointed to by the delegate
function
public static void DisplayA()
{
Console.WriteLine("Hello world");
}
Console.Read();
}
}
}
namespace Demo
{
class Program
{
// This is the method which will be pointed to by the delegate
function
public static void DisplayA(int i)
{
Console.WriteLine("The integer value is "+i);
}
Example 31: This program showcases the way to use a delegate with
class objects.
using System;
using System.IO;
namespace Demo
{
class Student
{
// Defining the members
private int id;
private string name;
private int subjectID = 1;
public int ID
{
get
{
return id;
}
set
{
id = value;
}
}
class Program
{
// Defining the delegate
public delegate void Del();
// The main function
static void Main(string[] args)
{
Student stud1 = new Student();
stud1.ID = 1;
stud1.Name = "John";
//Assigning the method to the delegate
Del handler = stud1.Display;
Example 32: The following program shows how to use Type to get
information on a class
using System;
using System.IO;
namespace Demo
{
class Student
{
// Defining the members
public int id;
public string name;
class Program
{
// The main function
static void Main(string[] args)
{
Student stud1 = new Student();
Example 33: The next program showcases the way to use MethodInfo.
using System;
using System.IO;
using System.Reflection;
namespace Demo
{
class Student
{
// Defining the members
public int id;
public string name;
class Program
{
// The main function
static void Main(string[] args)
{
Collections are special classes in C# that can make working with special
data classes considerably easier.
For example, instead of writing special code to find out the size of an
array, we can use the built-in function of the arrayList collection, called
size(), to get the size of the array. Hence, collections are specialized
classes that can be used in C# programs.
The collections below are present in C#:
ArrayList - The array container is used to store a contiguous set of
values of the same data type.
SortedList - Lists are sequence containers that allow constant time
insert and erase operations anywhere within the sequence, and
iteration in both directions.
Stacks - This is a type of collection specifically designed to operate
in a LIFO (last-in first-out) context, where elements are inserted and
extracted only from one end of the container.
Queues - This is a type of collection specifically designed to operate
in a FIFO (first-in first-out) context, where elements are inserted into
one end of the container and extracted from the other.
Let’s look at each collection in more detail.
9.1 ArrayList
The arrayList container is used to store a contiguous set of values of the
same data type. Let’s look at the definition of an array container via a
sample code.
The syntax for defining an array container is as follows:
ArrayList variablename=new ArrayList():
Here, ‘element’ refers to the value that needs to be added to the array list.
To view the element, we can simply reference it via the index number.
Let’s now look at an example on how to use the ArrayList collection.
Example 34: The following program is used to show the way to use
array lists.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Console.Read();
}
}
}
We can add any type of data type to the array list. Let’s look at an
example of an ArrayList of Strings.
Example 35: This program shows the way to use array lists of strings.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Console.Read();
}
}
}
Now let’s look at each function individually and how they work.
9.2.1 Size Function
This property is used to get the size of the ArrayList.
Example 36: The following program shows how to use count property.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Console.Read();
}
}
}
Example 37: The following program showcases the way to use clear
method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Example 38: The next program shows how to use the contains method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Example 39: The following program is used to show the way to use the
IndexOf method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Example 41: The following program is used to showcase the way to use
the remove method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
// Removing a value
ar.Remove(2);
Example 42: This program shows the way to use the RemoveAt method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
// Removing a value
ar.RemoveAt(1);
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Console.Read();
}
}
}
Example 44: The program below is used to showcase the way to use the
sort method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Console.Read();
}
}
}
Example 45: The following program shows how to use the GetRange
method.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the ArrayList
ArrayList ar = new ArrayList();
Here, ‘element’ is the value that needs to be added to the stack. Let’s now
look at an example of how to use the Stack collection.
Example 46: The following program showcases the way to use stacks.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
Console.Read();
}
}
}
The Stack class has a variety of operations that can be performed. Let’s
look at each one of these operations in more detail.
9.4 Stack Operations
The section below summarizes the details of the various operations
available for stacks.
Example 47: The next program shows how to use the count property.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
Example 49: The program below is used to showcase the way to use the
pop function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
Example 50: The following program is used to show how to use the peek
function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
Example 51: The next program shows the way to use the ToArray
function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
object[] ar1 = new object[3];
Console.Read();
}
}
}
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Stack
Stack ar = new Stack();
Here, ‘element’ is the value that needs to be added to the Queue. Let’s
now look at an example of how to use the Queue collection.
Example 53: The following program is used to showcase the way to use
queues.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
Console.Read();
}
}
}
The Queue class has a variety of operations that can be performed. Let’s
look at each one of these operations in more detail.
9.6 Queue Operations
The section below shows the details of the various operations available for
queues.
Example 54: The program below is used to showcase the count property.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
Example 55: The following program shows how to use the DeQueue
function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
Console.Read();
}
}
}
Example 56: The following program is used to showcase the way to use
the clear function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
Example 58: The following program shows how to use the ToArray
function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the Queue
Queue ar = new Queue();
Object[] ar1 = new Object[3];
ar1 = ar.ToArray();
Console.Read();
}
}
}
Where each element consists of a key and a value. Let’s now look at an
example of how to use the SortedList collection.
Example 59: The next program is used to show the way to use
SortedList.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Console.Read();
}
}
}
Example 60: The program below is used to showcase the way to use the
count property.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Example 62: The following program is used to show how to use the
ContainsKey function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Console.Read();
}
}
}
Example 64: The next program is used to show the way to use the
IndexOfKey function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Console.Read();
}
}
}
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Console.Read();
}
}
}
Example 67: The program below is used to show how to use the
RemoveAt function.
using System;
using System.Collections;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
// Defining the SortedList
SortedList ar = new SortedList();
Console.Read();
}
}
}
namespace Demo
{
class Program
{
// Display method for Integers
public static void Add(int i)
{
Console.WriteLine(“The value is “ + i);
}
Now in the above program, we are creating two methods that perform the
same function of adding two numbers. However, we need to create two
methods, one for the integer type and the other for the double data type.
Let’s see how we can make this program more generic by using the
‘Generic’ data type.
Example 69: The next program shows how to use the generic data type.
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
// Generic Display method
public static void Display<T>(T i)
{
Console.WriteLine(" The value is " + i);
}
Console.Read();
}
}
}
In this code, ‘classname’ is the name of the class. Let’s look at an example
of a generic class.
Example 70: The program below showcases the way to use the generic
class.
using System;
using System.Collections.Generic;
namespace Demo
{
// Generic class
public class GenericSet<T>
{
private T[] array;
public GenericSet(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Program
{
// The main function
static void Main(string[] args)
{
Console.Read();
}
}
}
Example 71: The following program is used to showcase the way to work
with events.
using System;
using System.Collections.Generic;
namespace Demo
{
public delegate string newDel(string str);
class EventClass
{
event newDel MyEvent;
public void TriggerEvent()
{
this.MyEvent += new newDel(this.mymethod);
}
class Program
{
// The main function
static void Main(string[] args)
{
EventClass evt = new EventClass();
Console.WriteLine("" + evt.mymethod("World"));
Console.Read();
}
}
}
Threads are used for concurrent programming. All systems are designed to
run programs as threads, which can run concurrently. Hence programming
languages also have the facility to support threaded programming. By
running threads, one can run multiple code side by side, and get added
results in a shorter duration of time.
In C#, there is a separate ‘Thread’ class available. The steps to work with
threads are as follows:
First define a method that will be called when the thread has started
execution.
Next use the ‘ThreadStart’ type to define a reference to the method.
Define a thread with the ‘Thread’ class.
Then attach the ‘ThreadStart’ type reference to the created object.
Lastly, use the start function to start the thread.
Let’s look at a simple example of how to create a thread and implement
the above steps.
namespace Demo
{
class Program
{
// This method will be called by the thread
public static void ThreadModule()
{
Console.WriteLine("The thread is starting");
}
Console.Read();
}
}
}
There are various functions available with threads. Let’s look at them in
more detail.
Example 73: The following program showcases how to use the isAlive
property.
using System;
using System.Threading;
namespace Demo
{
class Program
{
// This method will be called by the thread
public static void ThreadModule()
{
Console.WriteLine("The thread is starting");
}
Console.Read();
}
}
}
Example 74: This program is used to show the way to use the name
property.
using System;
using System.Threading;
namespace Demo
{
class Program
{
// This method will be called by the thread
public static void ThreadModule()
{
Console.WriteLine("The thread is starting");
}
Console.Read();
}
}
}
namespace Demo
{
class Program
{
// This method will be called by the thread
public static void ThreadModule()
{
Console.WriteLine("The thread is starting");
}
Console.Read();
}
}
}
Example 76: The next program shows how to use the ThreadState
property.
using System;
using System.Threading;
namespace Demo
{
class Program
{
// This method will be called by the thread
public static void ThreadModule()
{
Console.WriteLine("The thread is starting");
}
Console.Read();
}
}
}
Example 77: The following program is used to showcase the way to use
regular expressions.
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
// The main function
static void Main(string[] args)
{
String src = "Hello World";
string pattern = @"Hello";
Let’s look at another example where we can use regular expressions to get
digits that are embedded in a string.
Example 78: The following program also shows how to use regular
expressions.
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string input = "Let's have the number of 2000";
Once a match is found using regular expressions, we can also use the
length and index property to get the length of the found string and the
index in the source string where the match string was found.
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
string input = "Let's have the number of 2000";
Console.ReadKey();
}
}
}
With this program, the output is as follows:
The number in the string is 2000
The length of the derived value is 4
The index in the string where the value was found is 25
Conclusion
We have unfortunately reached the end of this guide, but as I always say,
it doesn’t mean your C# journey should end here. Practice as much as
possible. This book was written not only to be a teaching guide, but also a
reference manual. So remember to always keep it near, as you venture
through this wonderful world of programming.
If you enjoyed this guide, and this series, be sure to look into the other
programming languages I cover. I’m sure you would love them too.
About the Author