Reputation: 24067
Sorry I'm newbie in C# and events especially. Why I receive NPE?
class WcfModel : IWcfModel
{
private List<ConsoleData> _dataList;
public List<ConsoleData> DataList
{
get { return _dataList; }
set { _dataList = value;
DataArrived(_dataList); // NPE
}
}
public event Action<List<ConsoleData>> DataArrived;
}
Upvotes: 0
Views: 95
Reputation: 499062
If no object subscribed to the event (that is the delegate has no subscribers), it will be null
. You need to test for that:
set {
_dataList = value;
var dataDel = DataArrived;
if(dataDel != null)
dataDel(_dataList);
}
Alternatively, use ObservableCollection<ConsoleData>
- it has built in events for changes to the collection.
Upvotes: 3
Reputation: 2103
You should add a null checker for the event as the following codes:
class WcfModel: IWcfModel
{
private List<ConsoleData> _dataList;
public List<ConsoleData> DataList
{
get { return _dataList; }
set
{
_dataList = value;
if ( DataArrived != null )
DataArrived ( _dataList );
}
}
public event Action<List<ConsoleData>> DataArrived;
}
Upvotes: 0
Reputation: 19217
Rather use ObservableCollection<ConsoleData>
which has its own event publisher.
class WcfModel : IWcfModel
{
private ObservableCollection<ConsoleData> _dataList;
public WcfModel ()
{
_dataList = new ObservableCollection<ConsoleData>();
_dataList.CollectionChanged += DataArrived
}
public ObservableCollection<ConsoleData> DataList
{
get { return _dataList; }
}
public event Action<object, NotifyCollectionChangedEventArgs> DataArrived;
}
Now whenever you do
wcfModelInstance.DataList.Add(new ConsoleData("hello"));
You will be notified when you subscribe DataArrived
event in WcfModel
.
Hope this helps.
Upvotes: 1