c# - Null exception happens during an event trigger -
this question has answer here:
- what nullreferenceexception, , how fix it? 32 answers
so, been trying learn c# bit more ran wall when trying figure out how use events correctly.
needless say, keep getting null reference exception thrown when event trigger when value inputed event isn't null. appreciated.
code:
public delegate void performdespoit(int value); class bank { private int savingsgoal = 500; private int balance; //private int deposit; public event performdespoit valuechanged; public event performdespoit savingsreached; public int dep { set { this.balance = value; this.valuechanged(balance); if (balance > savingsgoal) { this.savingsreached(balance); } } } } class program { static void main(string[] args) { bank oldman = new bank(); string str; // holds response user int dep; // holds value deposit { console.writeline("please enter numerical value deposit:"); str = console.readline(); if (!str.equals("exit")) { dep = convert.toint32(str); oldman.dep = dep; } } while (!str.equals("exit")); } static void valuechanged(int value) { console.writeline("the current balance amount {0}", value); } static void savingsreached(int value) { //something console.writeline("something happens"); } } }
the nullreferenceexception throws when trying access not existing/defined. here in case have not assigned events , trying trigger it. lead throwing exception. need assign events following:
bank oldman = new bank(); oldman.valuechanged += new performdespoit(valuechanged); oldman.savingsreached += new performdespoit(savingsreached);
Comments
Post a Comment