views:

325

answers:

3

Why does the following line "alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);" gives me "An object reference is required for the non-static field, method, or property 'AlarmClock.Alarm.alarm_Sound(object, System.EventArgs)'"

   public static void Main(string[] args)
    {
        Alarm alarm = new Alarm(new DateTime(2010, 4, 7, 23, 2, 0));
        alarm.Set();
        alarm.AlarmEvent += new AlarmEventHandler(alarm_Sound);            
    }

Full source code here: Program.cs AlarmEventArgs

+4  A: 

Your alarm_Sound method is an instance method, meaning that it can only be used on an instance of your class.
Since Main is a static method, it is not associated with an instance of the class, so you cannot use any instance methods in it.

You need to make your alarm_Sound handler method a static method by adding the static keyword to its declaration.

Alternatively, you could create an instance of the class, then reference the handler method of that instance.

SLaks
I thought by doing "Alarm alarm = new Alarm(new DateTime(2010, 4, 7, 23, 2, 0));" I have already created an instance?
yeeen
@yeeen: Then you need to use that instance by adding `alarm.alarm_Sound`.
SLaks
Can compile alr. But, it doesn't work. It prints out "hey!" from my AlarmEventArgs constructor and continues looping. The event alarm_Sound doesn't get invoked (no "Ring ring ring!"), how come?
yeeen
A: 

Because the alarm_Sound method is defined in the context of the Class named Alarm in the Program.cs file, so, for calling it, you would need a instance of that class.

It would be better to define it as static so you don't need an instance for calling that method

Jhonny D. Cano -Leftware-
+1  A: 

You're adding the event handler after calling the Set method.
Therefore, when the Set method raises the event, it doesn't have a handler yet.

SLaks