Partial Class Instance Initialization Null Reference Exception - c#

I have a service with reference code below:
[System.Xml.Serialization.SoapTypeAttribute(Namespace="urn:customer")]
public partial class Receipt : object, System.ComponentModel.INotifyPropertyChanged {
private int counternoField;
private double activekwhField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute("counter-no")]
public int counterno {
get {
return this.counternoField;
}
set {
this.counternoField = value;
this.RaisePropertyChanged("counterno");
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute("active-km")]
public double activekm {
get {
return this.activekm Field;
}
set {
this.activekmField = value;
this.RaisePropertyChanged("activekm");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
[System.Xml.Serialization.SoapTypeAttribute(Namespace="urn:customer")]
public partial class ArrayOfReceipt : object, System.ComponentModel.INotifyPropertyChanged {
private Receipt[] itemField;
/// <remarks/>
public Receipt[] item {
get {
return this.itemField;
}
set {
this.itemField = value;
this.RaisePropertyChanged("item");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
And, when I want to create an instance of "ArrayOfReceipt" or set a value, or access it, I always encounter the same problem: System.NullReferenceException.
This is the code when I try to create:
var prev_Cons = new myService.Receipt();
prev_Cons.counterno = 1;
prev_Cons.activekm = 3265;
myService.ArrayOfReceipt prev_ConsArr = new myService.ArrayOfReceipt();
prev_ConsArr.item.SetValue(prev_Cons, 0);
Unfortunatelly, prev_ConsArr.item is always null, and I cannot initialize it. Please show me a way to initialize and set some value to this object. Thanks in advance.

The way your code is written, you can initialize prev_ConsArr.item like this:
prev_ConsArr.item = new Receipt[3];
That would create a new ArrayOfReceipt that could hold three Receipt objects. You could also create a constructor for your ArrayOfReceipt class that initializes item. Either of these methods will eliminate your NullReferenceException
Looking at the way you are using your ArrayOfReceipt class, you may want to consider changing the type of item to List<Receipt>. That would make it easier to change the number of Receipt classes you are storing.
Depending on what you are trying to do, you may also want to create an AddReceipt method in ArrayOfReceipts and move yourPropertyChanged event to that method. Right now, the PropertyChanged event will only fire when your ArrayOfReceipts class overwrites its array of Receipts.

Related

structs and INotifyPropertyChanged

I'm trying to add properties to my Model playing with my first MVVM app.
Now I want to add a place to save specific data in a clean way, so I used a struct.
But I am having issues to notify property changed, it does not have access to the method (An object reference is required for the non-static field)
Can someone explain to me why this happens and inform me on a strategy that fit my needs?
Thanks!
public ObservableCollection<UserControl> TimerBars
{
get { return _TimerBars; }
set
{
_TimerBars = value;
OnPropertyChanged("TimerBars");
}
}
public struct FBarWidth
{
private int _Stopped;
public int Stopped
{
get { return _Stopped; }
set
{
_Stopped = value;
OnPropertyChanged("Name"); //ERROR: An object reference is required for the non-static field
}
}
private int _Running;
//And more variables
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
OnPropertyChanged needs to be defined in the scope that you wish to update properties on.
For that to work you'll have to implement the interface INotifyPropertyChanged.
And finally you have to provide the correct argument to the OnPropertyChanged method. In this example "Stopped"
public struct FBarWidth : INotifyPropertyChanged
{
private int _Stopped;
public int Stopped
{
get { return _Stopped; }
set
{
_Stopped = value;
OnPropertyChanged("Stopped");
}
}
private int _Running;
//And more variables
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Edit: In your comment you mentioned that you've got a class sorounding the code you provided in your example.
That means you've nested a struct inside a class.
Just because you've nested your struct, doesn't mean it inherits properties and methods from the outer class. You still need to implement INotifyPropertyChanged inside your struct and define the OnPropertyChanged method inside it.

How to implement INotifyPropertyChanged for derived classes?

I have a base class:
public class PersonBaseClass : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
}
and a derived class
public class TeacherClass : PersonBaseClass, INotifyPropertyChanged
{
private string id;
public string Id
{
get { return id; }
set
{
if (value != id)
{
id = value;
NotifyPropertyChanged("Id");
}
}
}
}
and this magic code at the end of each one above!
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Then I show a list of Teachers collection in a list in xaml. Now if I change Id, changes will appear for user, but changes in Name which is a property in base class doesn't appear. In debug, I see after setting Name value, the handler inside NotifyPropertyChanged method is null which seems it is the problem.
How can I solve it to changes of base class also appear in the list?
Have only PersonBaseClass implementing INotifyPropertyChanged and make NotifyPropertyChange as protected so you can call it from child classes. There is not need to implement it twice. That should fix the problem as well.
Your "magic code" section should only be in PersonBaseClass. You can make the NotifyPropertyChanged function protected so that the same function can be called from TeacherClass as well.

Property Change event is null even after I registered it

I use INotifyPropertyChanged to notify class when there is any change in a variable of a particular object within it.
Below is the class:
public class MyClass
{
public SecClass MyObj { get; set; }
//A few more variables
}
SecClass:
public class SecClass:INotifyPropertyChanged
{
private bool _noti= false;
public bool Noti
{
get { return _noti; }
set
{
_noti= value;
NotifyPropertyChanged("Noti");
}
}
//A few more variables
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
Here my function that makes the event registration:
public void Register()
{
MyObj.PropertyChanged += MyObj_PropertyChanged;
}
Function works and the registration is done, but when it comes to change it displays the Property Change as null (I guess that somewhere registration deleted, before happens change, how can I check this?)
I hooked this together with:
static class Program
{
static void Main()
{
var c = new MyClass();
c.MyObj = new SecClass();
c.Register();
c.MyObj.Noti = !c.MyObj.Noti;
}
}
adding (for illustration):
private void MyObj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(e.PropertyName);
}
to MyClass, and:
public event PropertyChangedEventHandler PropertyChanged;
to SecClass (to get them to compile), and it works fine - printing "Noti" at runtime. There is a theoretical thread-race, but it is very unlikely in any sane usage, but recommended usage is:
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
Also, for info: if you add [CallerMemberName] to that, you don't need to specify the property explicitly:
private void NotifyPropertyChanged([CallerMemberName] string name = null) {...}
with:
NotifyPropertyChanged(); // the compiler adds the "Noti" itself
But fundamentally: "cannot reproduce" - it works fine. I wonder if maybe it relates to your PropertyChanged implementation, since you don't actually show that. In particular, I wonder if you actually have two events: one explicitly implemented. That would mean that it is getting treated differently by your cast.

creating a ViewModel class

I would like to create a ViewModel Class to retrieve the values from the Database.
My goal is to retrieve the Values of Usage of RAM (Ram total & Ram available) from my DB Table and then display it on my View.
This is what I have done so far on my ViewModel Class
public class RamViewModel : INotifyPropertyChanged
{
float _ramTotal;
float _ramUsed;
public float RamTotal
{
get { return _ramTotal; }
set { _ramTotal = value; RaisePropertyChanged("RamTotal"); }
}
public float RamUsed
{
get { return _ramUsed; }
set { _ramUsed = value; RaisePropertyChanged("RamUsed"); }
}
private void RaisePropertyChanged(string p)
{
throw new NotImplementedException();
}
}
when I build the class, I got this error stating, " ViewModel.RamViewModel Does not implement interface member 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'"
How to overcome this error
INotifyPropertyChanged is an interface with one member that needs to be included in your class definition:
public event PropertyChangedEventHandler PropertyChanged;
You should also change the code in RaisePropertyChanged to not throw an exception, by implementing the actual functionality:
private void RaisePropertyChanged(string p)
{
if (null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(p));
}
Your class does not expose the PropertyChanged event, which is necessary for classes that implement INotifyPropertyChanged (it's the only member of that interface).
So you should add:
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName);
}
}
ObservableCollection is unrelated to this.

Calling OnPropertyChange("property_name") Sends Updates to All Bound Properties

So I have a class with 40 or so properties that are updated from communication with a micro controller. This class implements INotifyPropertyChanged.
Loose Example:
private int _Example;
public int Example
{
get
{
return _Example;
}
set
{
_Example = value;
OnPropertyChange("Example");
}
}
And the OnPropertyChange function:
protected void OnPropertyChange(string p_Property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p_Property));
}
}
public event PropertyChangedEventHandler PropertyChanged;
Binding (many of these)
Second_Class_Control.DataBindings.Clear();
Second_Class_Control.DataBindings.Add("My_Property", FirstClass, "Example");
In the main form I've set up binds to display and react to these values. One of those happens to land on another property in a another class. I happened to place a breakpoint in the set function of this property, and noticed it was being called any time any property from the first class changed.
Is this the correct behavior? I don't notice any performance hits but I plan on having many instances of these classes running together and wasn't expecting this.
Thanks
Hmm.. I noticed that you have the your OnPropertyChange virtual. Why is this, are you making a override somewhere?
I usually creates it like this :
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
then for the usage :
public class MainWindowViewModel : ViewModelBase
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
}

Categories

Resources