Using events/delegates in C#

This example demonstrates the use of delegate in C#. The example consists of a class named Class1.cs and a form named Form1. The class has an attribute named Property1 and implements the use of delegate by having an event fired when the property changes.
The Form contains a textbox and a button. When the user clicks the button, it initializes the class and sets its attribute (Property1) to "testProperty". The value set will automatically be displayed at the textbox once the event fires.


//Class1.cs
//***********************************************************************************
using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsApplication1
{
public class Class1
{
public delegate void ValueSet();
public event ValueSet OnValueSet;

private string _property1;

public string Property1
{
get { return _property1; }
set {
_property1 = value;
OnValueSet();
}
}

}
}
//Form1.cs
//***********************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
Class1 c;
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
c = new Class1();
c.OnValueSet += new Class1.ValueSet(c_OnValueSet);
c.Property1 = "testProperty";
}

void c_OnValueSet()
{
textBox1.Text = c.Property1;
}

}
}

More codes at codelinquent forum

Comments

0 Responses to "Using events/delegates in C#"