Unit IV
Properties, Indexers, Delegates & Events
Properties
Properties are data members of a class using which we can expose values associated with
a class outside the class environment.
A Property in C# is used to set and get data from a data field i.e. variable of a class. It is
never used to store any data, it just acts an interface to transfer the data outside the class.
We use the properties as public data members of a class but they are actually contains
special methods called as accessors. The Accessors are nothing but the special methods which are
used to set and get the values from the data member of a class. This enables data to be accessed
easily and helps to promote the safety and flexibility of methods.
Property can be following types:
1. Read/Write Properties: A property with both get and set accessor is a Read-Write
property.
2. Read Only Properties: A property with only get accessor is a Read only property.
3. Write Only Properties: A property with only set accessor is a Write only property.
In C#, we use get and set accessors to implement properties.
Syntax –
<Access_Specifier> <type> <Property_Name>
{
get { // get statements } // Only get property is read only
set { // set statements } // Only set property is write only
// when get and set then property is read-write
}
Program – Write a program to demonstrate concept of properties in C#.
namespace propertiesExample
{
public partial class Form1 : Form
{
1
public Form1( )
{
InitializeComponent( );
}
private void btn_set_Click(object sender, EventArgs e)
{
number c = new number( );
txt_first.Text = ([Link]).ToString( );
[Link] = 10;
txt_second.Text = ([Link]).ToString( );
}
private void btn_exit_Click(object sender, EventArgs e)
{
[Link]( );
}
}
public class number
{
int no = 5;
public int noProperty // Property definition
{
get { return no; }
set { no = value; }
}
}
}
Output:
2
Indexers
C# introduces a new concept called as Indexers in which object is treated as array. When
we define an indexer for a class, then that class behaves similar to a virtual array. We can then
access the instance of this class using the array access operator ([ ]).
Declaration of behavior of an indexer is to some extent similar to a property. Similar to the
properties, we have to use get and set accessors for defining an indexer. However, properties
return or set a specific data member, whereas indexers returns or sets a particular value from the
object instance.
Defining a property involves providing a property name. Indexers are not defined with
names, but with the this keyword, which refers to the object instance.
Syntax –
<Access_Specifier> <type> this[<parameter type> index]
{
get { // get statements } // Only get property is read only
set { // set statements } // Only set property is write only
// when get and set then property is read-write
}
The following example demonstrates the concept of Indexer –
3
namespace indexerExample
{
public partial class Form1 : Form
{
public Form1( )
{
InitializeComponent( );
}
private void btn_display_Click(object sender, EventArgs e)
{
Student s = new Student(10, "Ram");
txt_rn.Text = (s[0]).ToString( );
txt_name.Text = (s[1]).ToString( );
s[0] = 20;
s[1] = "Sham";
txt_setrn.Text = (s[0]).ToString( );
txt_setname.Text = (s[1]).ToString( );
}
private void btn_exit_Click(object sender, EventArgs e)
{
[Link]( );
}
}
public class Student
{
int stud_rn;
string stud_name;
public Student(int rn, string name)
{
this.stud_rn = rn;
this.stud_name = name;
}
public object this[int index]
{
4
get
{
if (index == 0)
return stud_rn;
else if (index == 1)
return stud_name;
return null;
}
set
{
if (index == 0)
stud_rn = (int)value;
else if (index == 1)
stud_name = (string)value;
}
}
}
}
5
Delegates
Delegate is a type safe function. C# delegates are similar to pointers to functions, in C or
C++. A delegate is a reference type variable that holds the reference to a method. The reference
can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the [Link] class.
Syntax –
Step 1: Define a Delegate
<access_modifier> delegate <return type> <delegate_name> (<parameters>);
Step 2: Create an Instance of a Delegate
<delegate_name> <del_object_name> = new <delegate_name> (<method_name>);
Step 3: Invoking a Delegate
<del_object_name> (<parameters>);
Example –
The following program demonstrates multicasting of a delegate –
namespace delegateExample
{
public delegate double dollarDelegate(double n); // Step 1 - define a delegate
public partial class Form1 : Form
{
public Form1( )
{
InitializeComponent( );
}
private void btn_convert_Click(object sender, EventArgs e)
{
double amount = [Link](txt_rs.Text);
Conversion obj = new Conversion( );
dollarDelegate dd = new dollarDelegate([Link]); // Step 2 - Delegate instantiation
6
txt_dollar.Text = (dd(amount)).ToString( ); // Step 3 - Delegate Invocation
}
private void btn_exit_Click(object sender, EventArgs e)
{
[Link]( );
}
}
public class Conversion
{
public double dollar(double x)
{
return x / 70;
}
}
}
Output:
7
Multicast Delegate
The delegate can points to multiple methods. A delegate that points multiple methods is
called a multicast delegate. Delegate objects can be composed using the "+" operator.
A composed delegate calls the two delegates it was composed from. Only delegates of the
same type can be composed. The "-" operator can be used to remove a component delegate from
a composed delegate.
The following program demonstrates multicasting of a delegate –
namespace multicastDelegate
{
public delegate double currencyDelegate(double n);
public partial class Form1 : Form
{
public Form1( )
{
InitializeComponent( );
}
private void btn_convert_Click(object sender, EventArgs e)
{
double amount = [Link](txt_rs.Text);
Currency obj = new Currency( );
currencyDelegate cd = new currencyDelegate([Link]);
txt_dollar.Text = (cd(amount)).ToString( );
cd += [Link];
txt_euro.Text = (cd(amount)).ToString( );
}
private void btn_exit_Click(object sender, EventArgs e)
{
[Link]( );
}
}
public class Currency
{
public double dollar(double x)
{
return x / 70;
}
8
public double euro(double x)
{
return x / 90;
}
}
}
Output:
9
Custom Events
Events are user actions such as key press, clicks, mouse movements etc. We can define our
own events to controls, known as custom events.
Using Delegates with Events
The events are declared and raised in a class and associated with the event handlers using delegates
within the same class or some other class.
The class containing the event is used to publish the event. This is called the publisher class. Some
other class that accepts this event is called the subscriber class. Events use the publisher-
subscriber model.
A publisher is an object that contains the definition of the event and the delegate. A publisher class
object invokes the event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in the
publisher class invokes the method (event handler) of the subscriber class.
Design a Windows Application to demonstrate the concept of Custom Event in C#.
Coding:
using System;
using [Link];
namespace CustomEventEx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
10
//Manually registering the button’s click event
[Link] += new EventHandler(Button_Click);
}
private void Button_Click(object sender, [Link] e)
{
[Link] = "Custom Event";
}
}
}
Output:
Explanation to above Program:
To add a custom event to button control we have to use the delegate EventHandler which will fire
when we click the button control. It takes the reference of a method as a parameter to execute the
specified registered event.
When the program is running, the system will check if this.button1 is clicked, and if clicked,
Button1_Click() method will be executed.
The expression after the equal to sign is an instance of a delegate type ([Link]) which
acts as a handler for the registered event.
Use of “object sender” and “EventArgs e” parameters in above Program:
These two parameters sender and e are sent by convention with all events where
The object keyword referes to the object which activated the event. This is being placed in the
variable called sender.
The EventArgs is a class, Where e is a parameter used for passing associated event data.
11
Example for adding dynamic event to controls at runtime:
Here, while working on a winforms app in C#, if we have added some controls dynamically
(eg. Button) then we can add an event to that created button as below:
Design View:
Coding:
namespace CustmEventEx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
[Link] = "Display";
[Link] += new EventHandler(ShowMessage);
[Link](b);
}
private void ShowMessage(object sender, EventArgs e)
{
[Link]("Message");
}
}
}
12
Output:
13