You are on page 1of 44

Session 6

Advanced C# Concepts II

Review

An assembly consists of:

A set of types and resources that form a logical unit of


functionality.

A manifest containing information that describes the


assembly.
We can deploy classes within the same namespace into
different assemblies, and classes within different
namespaces into one assembly.
Assemblies are of two types: Private Assemblies and Shared
Assemblies
The version number of an assembly is represented as a fourpart number in the following format: <Major version>.<
Minor version >.<Revision>.<Build Number>

C# Simplified / Session 6 / 2 of 44

Review Contd

The System.Reflection namespace contains around forty


classes and interfaces that can be employed to get
information about an object.
Collections are datatypes that provide us with a way to store
and collectively act upon data.
Exceptions are raised by the runtime when an error occurs.
The try and catch block helps in handling raised exceptions.
Using the Throw statement, we can either throw a system
exception, or our own custom exception.
The statements in the Finally block are executed regardless
of the control flow.

C# Simplified / Session 6 / 3 of 44

Objectives

Explain Properties

Discuss type of properties such as

Public

Private

Read-only

Write-only

Discuss Indexers

Implement Delegates

Define and Raise Events

C# Simplified / Session 6 / 4 of 44

Properties in C#

C# provides the facility to protect a field


in a class by reading and writing to it
through a feature called properties
C# properties enable a similar type of
protection while at the same time allows
access to the property like a field.
In general terms, a property would mean
the characteristics or information about
a particular entity.

C# Simplified / Session 6 / 5 of 44

Properties in C# - Contd

The general form for declaring the properties is


<access_modifier> <return_type>
<property_name>
{
get
{
}
set
{
}
}

where <access_modifier> can be private, public,


protected or internal. The <return_type> can be
any valid C# type.

C# Simplified / Session 6 / 6 of 44

Properties Get & Set


public class Employee
{
private String sName
private String sId
public string sId
{
get
{
return sId;
}
set
{
sId = value
}
}

C# Simplified / Session 6 / 7 of 44

Properties Get & Set


Each time we need to access the field we
need to call the set and get methods

Employee emp = new Employee();


emp.sId = S001;
Console.WriteLine("The student id is
{0}, emp.sId);
..

C# Simplified / Session 6 / 8 of 44

Properties - Example
using System;
public class Student
{
public string sName;
//Field
private string internal_sId;//Field
public string sId
//Property
{
get
{
return internal_sId;
}
set
{
internal_sId = value;
}
}
}

C# Simplified / Session 6 / 9 of 44

Properties Example Contd


class Test
{
static void Main()
{
Student one = new Student();
one.sName = "Sam";
one.sId = "St423";
Console.WriteLine("The Name of the Student is {0}
and his Id is {1}", one.sName, one.sId);
}
}

C# Simplified / Session 6 / 10 of 4

Properties - Explanation

C# Simplified / Session 6 / 11 of 4

Types of Properties

Public Properties: Users can access these


properties without any restrictions
Private Properties: are accessible to the
users only from inside the class or structure
where they are defined.
Read / Write Property: Provides both read
and write access to the data members.
Read - Only Property: Provides only read
access to the data members.
Write - Only Property: Provides only write
access to the data members.

C# Simplified / Session 6 / 12 of 4

Read-only Property - Example


public class Employee
{
private int empsalary = 15000;
//Field
public int EmpSalary
//Property
{
get
{
return empsalary;
}
}
}
class EmployeeTest
{

C# Simplified / Session 6 / 13 of 4

Read-only Property Output


static void Main()
{
Employee objEmployee = new Employee();
System.Console.WriteLine ("The salary of the
Employee is {0}", objEmployee.EmpSalary);
objEmployee.EmpSalary = 25000; //error }
}

C# Simplified / Session 6 / 14 of 4

Properties Vs Fields

Properties are logical fields

Properties are an extension of


fields

Unlike fields, properties do not


correspond directly to a
storage location

C# Simplified / Session 6 / 15 of 4

Property Accessors

Accessors of properties contain the


statements that are to be executed when
a property is get /set
The accessor declarations can contain the
get accessor or the set accessor or both.
The get accessor is similar to any
method that returns a value
The set accessor is similar to a method
that returns a void

C# Simplified / Session 6 / 16 of 4

Indexers

Indexers are simple components of C#

Created for arrays so that the elements


are accessed directly by specifying the
index from the class object

Allow an object to be indexed in the


same way as an array

Enable array-like access to the


members of the class

C# Simplified / Session 6 / 17 of 4

Indexers - Example
class IndexerExample
{
public string[] stringList =new string[10];
public string this[int index]
{
get
{
return stringList[index];
}
set
{
stringList[index] = value.ToString();
}
}
}

C# Simplified / Session 6 / 18 of 4

Indexers - Output
class Test
{
static void Main()
{
IndexerExample indexTest = new IndexerExample();
indexTest.stringList[1]="Sam";
indexTest[2]="Tom";
System.Console.WriteLine("indexTest[1] is
{0}\nindexTest[2] is {1}", indexTest[1], indexTest[2]);
}
}

C# Simplified / Session 6 / 19 of 4

Steps for declaring an Indexer

The access modifier that decides the


visibility of the indexer is to be mentioned
State the return type of the indexer
The this keyword
Specify the data type of the index
State the variable name for the index
Specify the get and set accessors inside
the indexer

C# Simplified / Session 6 / 20 of 4

Rules for defining an Indexer

At least one Indexer parameter


must be specified

The parameters should be


assigned values

C# Simplified / Session 6 / 21 of 4

Indexers vs. Arrays

Indexers do not point to memory


locations

Indexers can have non integer


subscripts (indexes)

Indexers can be overloaded

C# Simplified / Session 6 / 22 of 4

Indexer Example 1
using System.Collections;
class StrIndex
{
public Hashtable studentList = new Hashtable();
public int this[string name]
{
get
{
return (int) studentList[name];
}
set
{
studentList[name] = value;
}
}
}

C# Simplified / Session 6 / 23 of 4

Indexer Example 1
Contd
class Test
{
static void Main()
{
StrIndex objIndex = new StrIndex();
objIndex ["Sam"] = 232676;
objIndex ["Tom"] = 455464;
System.Console.WriteLine ("Phone number
of Sam is {0} and Phone number of Tom
is {1}", objIndex ["Sam"],
objIndex["Tom"]);
}
}

C# Simplified / Session 6 / 24 of 4

Indexer Example - 2
using System.Collections;
class IndexerExample
{
public string[] stringList = new string[10];
public string this[int index]
{
get
{
return stringList[index];
}
set
{
stringList[index] = value.ToString();
}
}
public Hashtable studentList = new Hashtable();

C# Simplified / Session 6 / 25 of 4

Indexer Example 2
Contd
public int this[string number]
{
get
{
return (int) studentList [number];
}
set
{
studentList [number] = value;
}
}
}

C# Simplified / Session 6 / 26 of 4

Indexer Example 2
Contd
class Test
{
static void Main()
{
IndexerExample indexTest = new IndexerExample();
indexTest.stringList[1] = "Sam";
indexTest[2] = "Tom";
indexTest ["Sam"] = 232;
indexTest ["Tom"] = 455;
}
}

C# Simplified / Session 6 / 27 of 4

Using Multiple Parameters

More than one indexer parameter can be specified in an indexer


Multiple parameters would mean that the indexer would be
accessed like a multi-dimensional array

...
class TestMultip
{
public int this[int firstP, int secondP]
{
//Get and Set Accessors appear here
}
}
. . .

C# Simplified / Session 6 / 28 of 4

Using Multiple Parameters


Class TestIndexers with multiple indexer
parameters are accessed like a MultiDimensional Array.

{
void static Main()
{
TestMultip myTest = new TestMultip();
int I = myTest[1,1];
}
}

C# Simplified / Session 6 / 29 of 4

Delegates

Contain a reference to a method


Helps us decide, which method to call at
runtime
Technically, a delegate is a reference
type used to encapsulate a method with
a specific signature and return type.
Steps

Defining a delegate
Instantiating a delegate
Using a delegate

C# Simplified / Session 6 / 30 of 4

Defining Delegates
Defining a delegate involves specifying the
return types and parameters that each method
must provide
public delegate void
DelegateName();
...
public delegate int CallFunctions (int a, int b);

...

C# Simplified / Session 6 / 31 of 4

Instantiating Delegates
Instantiating a
class TestDelegates
{
delegate
public delegate int CallFunctions(int a, int b);
means making
class MathsOperations
it point (or
{
public int MultiplyFn(int a, int b)
refer) to some
{
method.
return a*b;
}
public int DivisionFn(int a, int b)
{
return a/b;
}
}

C# Simplified / Session 6 / 32 of 4

Instantiating Delegates
Contd
class Test
{
static void Main()
{
CallFunctions DelegateObj;
MathsOperations math = new
MathsOperations();
DelegateObj = new
CallFunctions(math.MultiplyFun);
}
}
}

C# Simplified / Session 6 / 33 of 4

Using Delegates
class TestDelegates
{
public delegate int CallFunctions(int num1, int
num2);
class MathsOperations
{
public int MultiplyFn(int num1, int num2)
{
return num1*num2;
}
public int DivisionFn(int num1, int num2)
{
return num1/num2;
}
}
}

Using a delegate means instantiating a method that uses


delegates.
C# Simplified / Session 6 / 34 of 4

Using Delegates - Contd


class Test
{
static void Main()
{
CallFunctions DelegateObj;
MathsOperations math = new MathsOperations();
DelegateObj = new CallFunctions(math.MultiplyFn);
int result=DelegateObj(5, 3);
System.Console.WriteLine ("The Result after
calling MultiplyFn is : {0}",result);
}
DelegateObj = new CallFunctions(math.DivisionFn);
int result1 = DelegateObj(5, 3);
System.Console.WriteLine ("The Result after
calling DivisionFn is : {0}\n",result1);
}

C# Simplified / Session 6 / 35 of 4

Using Delegates - Output

C# Simplified / Session 6 / 36 of 4

Events

Events in C# allow an object to notify other objects


about the event or that a change has occurred

The object that notifies the others about the event


is known as the Publisher

An object that registers to an event is known as


the Subscriber

Steps

Defining an Event
Subscribe objects to that event
Notify subscribers of the event

C# Simplified / Session 6 / 37 of 4

Defining Events

While defining an event the publisher

defines a delegate
defines an event based on the delegate

public delegate void delegateMe();


private event delegateMe eventMe;

C# Simplified / Session 6 / 38 of 4

Subscribing
Subscribing an object to an event
depends upon the existence of the
event
eventMe += new delegateMe(objA.Method);
eventMe += new delegateMe(objB.Method);

C# Simplified / Session 6 / 39 of 4

Notifying
To notify all the objects that have
subscribed to an event we just need
to raise the event
if(condition)
{
eventMe();
}

Raising an event is like calling a


method.

C# Simplified / Session 6 / 40 of 4

Events and Delegates-Example


using System;
class ClassA
{
public void DispMethod()
{
Console.WriteLine ("Class A has been notified of
NotifyEveryOne Event!");
}
}
class ClassB
{
public void DispMethod()
{
Console.WriteLine ("Class B has been notified of
NotifyEveryOne Event!");
}
}

C# Simplified / Session 6 / 41 of 4

Events and DelegatesExample


class Test
{
public static void Main()
{
TestDelegate dA = new TestDelegate();
ClassA objA = new ClassA();
ClassB objB = new ClassB();
dA.NotifyEveryOne += new
TestDelegate.MeDelegate (objA.DispMethod);
dA.NotifyEveryOne += new
TestDelegate.MeDelegate (objB.DispMethod);
dA.Notify();
}
}

C# Simplified / Session 6 / 42 of 4

Events and DelegatesExample


class TestDelegate
{
public delegate void MeDelegate();
public event MeDelegate NotifyEveryOne;
public void Notify()
{
if(NotifyEveryOne != null)
{
Console.WriteLine ("Raise Event : ");
NotifyEveryOne();
}
}
}

C# Simplified / Session 6 / 43 of 4

Summary

Properties provide the opportunity to protect a field in a class by


reading and writing it using accessors.
An indexer allows an object to be indexed in the same way as an
array.
A delegate contains a reference to a method rather than the method
name.
There are three steps involved in using delegates that are as follows.

Defining a Delegate
Instantiating a Delegate
Using a Delegate

Events in C# allow an object to notify other objects about the event,


or about a change that has occurred.
There are three steps involved to handle events in C# that are as
follows.

Defining an Event
Subscribing objects to that event
Notifying subscribers of the event (when it occurs)

C# Simplified / Session 6 / 44 of 4

You might also like