Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        Account MyAccount = new Account(10000);
        subscriber Mysubscriber = new subscriber();

        public Form1()
        {
            InitializeComponent();
            MyAccount.TransactionMade += new TransactionHandler(Mysubscriber.SendNotification);
        }

       
        private void ButtonCredit(object sender, EventArgs e)
        {
            MyAccount.Credit(500);
            MessageBox.Show("your current balance is ", MyAccount.BalanceAmount.ToString());
        }
    }
}



namespace WindowsFormsApp1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }


    public delegate void TransactionHandler(object sender, TransactionEventArgs e); // Delegate Definition
    class Account
    {
        public event TransactionHandler TransactionMade; // Event Definition

        public int BalanceAmount;

        public Account(int amount)
        {
            this.BalanceAmount = amount;

        }

        public void Debit(int debitAmount)
        {
            if (debitAmount < BalanceAmount)
            {
                BalanceAmount = BalanceAmount - debitAmount;
                TransactionEventArgs e = new TransactionEventArgs(debitAmount, "Debited");
                OnTransactionMade(e); // Debit transaction made
            }
        }

        public void Credit(int creditAmount)
        {

            BalanceAmount = BalanceAmount + creditAmount;
            TransactionEventArgs e = new TransactionEventArgs(creditAmount, "Credited");
            OnTransactionMade(e); // Credit transaction made

        }

        protected virtual void OnTransactionMade(TransactionEventArgs e)
        {
            if (TransactionMade != null)
            {
                TransactionMade(this, e); // Raise the event 
            }
        }

    }


    public class TransactionEventArgs : EventArgs
    {
        public int TranactionAmount { get; set; }
        public string TranactionType { get; set; }

        public TransactionEventArgs(int amt, string type)
        {
            TranactionAmount = amt;
            TranactionType = type;
        }
    }


    public class subscriber
    {

        public void SendNotification(object sender, TransactionEventArgs e)
        {
            //Console.WriteLine("Your Account is {0} for Rs.{1} ", e.TranactionType, e.TranactionAmount);
            MessageBox.Show(e.TranactionType);
            MessageBox.Show(e.TranactionAmount.ToString());
        }



    }
}


What I have tried:

this is console example i found. i try to make it to a winform. not sure whether i put the position right.
1. is it good practice to create MyAccount in that position? inside partial Class Form1, or should i put it in Class program Main()?

2. good to put event subscription in Form1()?
3. is it necessary to put unsubscription , where if needed?

learning Event! thank you!
Posted
Updated 23-Nov-17 6:17am
Comments
Iqra Ali 21-Nov-17 23:07pm    
Where is the code for console app? Your questions are unclear. Can you edit your concern with bit more clarity?
RaviRanjanKr 22-Nov-17 2:46am    
Please be more specific while asking question.

1 solution

Quite an unusual question.

Well first off 'Form1' is not good, always give meaningfull names :)

1. IMO it is a good principle with "One class, one file" principle, essentially placing every class is different files and that means no it's not a good place to define another class inside a Form class and it is equally bad to put in in your Main.cs file, which in terms is a bit worse because 'everybody' knows the main contains one static class called 'Program' with one static method called Main. Ultimately you'll likely put all business objects in a seperate dll away from the user interface in which case it's practical to be organized for the future, from the start.
If you mean putting members in the form? i.e. not definitions but instances, then that could be fine. However consider using a property instead. This way you get accessors and you can add your default only if it is being 'get' before being assigned and in real flow that will never happen. no reason to instantiate with a value which will never be relevant outside of development.

2. Yes. communicating out from a class should be using an event, why Your form should assign the eventhandler for another class is less clear but in principle it's fine, just remember to remove eventhandlers when destroying the form if the objects are to exist after the form or you can keep stuff alive for a very long time by reference.

3. Is it necessary to unsubscribe to events you subscribe to ? IMO always! But ultimately in your example your instances belong to the form so the event subscribers will not survive closing your form.
A form is a 'disposable' object, in .net your .Dispose method is the one being called by the garbage collector thread if you didn't dispose explicitly. Every so often it's going to traverse the memory for disposable object and look for references in user memory, if none exist, it will call dispose on the object. This makes it a handy place to unsubscribe.
 
Share this answer
 
v2

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