Click here to Skip to main content
15,914,222 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm trying to make an event in my Person Class that notifies other classes when the Cash property is >= 100. My code runs fine, but doesn't do anything.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {
            Person NewPerson = new Person();
            NewPerson.AddCash(150);
           NewPerson.Myevent += NewPerson_Myevent;

       }

        static void NewPerson_Myevent()
        {
            Console.WriteLine("Hello New Person");
        }

    }
    public class Person
    {
        public delegate void MyeventHandler();
        public event MyeventHandler Myevent;

        private int _cash = 50;
        public int Cash
        {
            get
            {
                return this._cash;
            }
            set
            {
                this._cash = value;
                if (this._cash >= 100)
                {
                    if (Myevent != null)
                    {
                        Myevent();
                    }
                }

            }

        }
        public void AddCash(int money)
        {
           Cash += money;
        }
    }
}
Posted
Updated 23-Mar-15 4:27am
v4
Comments
PIEBALDconsult 23-Mar-15 10:20am    
That sounds like a bad design. The event should be fired every time the Cash property is updated, then the consumers can decide what to do when.
Member 11481290 23-Mar-15 10:26am    
Thx for the comment. I will keep that in mind.

1 solution

You're adding the money before you attach the event. Reverse the order of the code

Person NewPerson = new Person();
NewPerson.Myevent += NewPerson_Myevent;
NewPerson.AddCash(150);
 
Share this answer
 
Comments
Member 11481290 23-Mar-15 9:49am    
Thx.
Sergey Alexandrovich Kryukov 23-Mar-15 10:30am    
Good catch, a 5. I would also strongly recommend anonymous event handler.
Also, the name "NewPerson_Myevent" violates Microsoft naming conventions, which I think are good enough and are very useful. Method names should be semantic. Auto-generated names (by designers, for example) are not intended to be used permanently, the always violate those naming conventions (for good reasons though :-).
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900