Class Creation with Events

  • Thread starter Thread starter Matt
  • Start date Start date
M

Matt

Can anyone point me in the direction of creating an event in a class I
develop? What I am looking for is finding a way that when a property gets
set or is changed a method is automatically run to perform validation or
anything else. Is it possible to put code in the get/set of properties?

Thanks,

Matt
 
Matt,
Do you just want to call a method, or do you want to trigger an event?
Either way I suppose could be done:

private string _myProperty = null;

public string MyProperty
{
get{return(this._myProperty);}
set
{
this._myProperty = value;
//make method call or trigger event here.
}
}
 
Hi there...

Yes it's possible... for example

using System;

class Test {
public delegate void MyDelegate(Object sender, DateTime time, int value);
public event MyDelegate OnFireMyEventSetterCalled;
public event MyDelegate OnFireMyEventGetterCalled;

private int m_count;

public int Count {
get {
if (OnFireMyEventGetterCalled != null)
OnFireMyEventGetterCalled(this, DateTime.Now, m_count);
return m_count;

}

set {
m_count = value;
if (OnFireMyEventSetterCalled != null)
OnFireMyEventSetterCalled(this, DateTime.Now, m_count);

}
}
}


class EntryPoint {

static void Main() {
Test x = new Test();
x.OnFireMyEventSetterCalled += new Test.MyDelegate(Setter);
x.OnFireMyEventGetterCalled += new Test.MyDelegate(Getter);
Console.WriteLine("Insert an integer: ");
x.Count = int.Parse(Console.ReadLine());
Console.WriteLine(x.Count);
Console.ReadLine();
}

static void Setter(Object sender, DateTime time, int value) {
Console.WriteLine("\nSetter Called!!!");
Console.WriteLine("Sender :"+sender.ToString());
Console.WriteLine("Time :"+time.ToString());
Console.WriteLine("value :{0}",value);

}

static void Getter(Object sender, DateTime time, int value) {
Console.WriteLine("\nGetter Called!!!");
Console.WriteLine("Sender :"+sender.ToString());
Console.WriteLine("Time :"+time.ToString());
Console.WriteLine("value :{0}",value);
}

}


Regards,
 
Back
Top