Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NullReferenceException on custom Class with Dictionary

I have a simple question today about some custom Classes that are not working as desired. For context, this is C# code in Xamarin Forms, building for UWP.

In my C# code, I have two custom classes. We will call them Smaller and Bigger. Smaller is a simple class that only has a few instance variables. My issue is with the Bigger class, which includes a dictionary mapping strings to instances of my Smaller class. When I try to create an Indexer for the Bigger class, I want it to index into the dictionary included in the class.

Here is the code with relevant parts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Smaller {
    ... // a bunch of instance variables, all strings, public and private versions.
}

public class Bigger {
    ...
    // other instance variables here...
    ...
    // the dictionary in question, mapping to Smaller instances
    private Dictionary<string, Smaller> _Info;
    public Dictionary<string, Smaller> Info {
        get => _Info;
        set { 
            _Info = value;
            OnPropertyChanged("Info");
        }
    }

    public Smaller this[string key] { // Indexer for Bigger class
        get => _Info[key];
        set => Info.Add(key, value);
    }
}

It is in the Indexer that I get my error, the NullReferenceException on my getter and setter. What is going wrong here? I have tried for both the getter and setter using the private _Info or public Info and neither one works for either.

The OnPropertyChanged don’t affect anything since I have other variables using them which work fine. Should I just get rid of having two variables, private and public? I am just doing that since the code is adapted from a template that uses the private and public instances.

Thanks!

>Solution :

this is null

private Dictionary<string, Smaller> _Info;

you need to initialize it

private Dictionary<string, Smaller> _Info = new Dictionary<string, Smaller>();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading