Search code examples
c#listpropertiesautomatic-properties

null exception with lists in c#


hey i am trying to work with a generic list in C# and for some reason after allocating memory for the list i am getting unhandeledNullException.

 //edit

i found out what was my problem i did not use the properties currectly. if lets say GeoInfo is a private member of my class, how do i do properties to it, i tried :

 private List<GeoInfo> GEOINFOS { get; set; } // edit i forgot to change it back 
// but i want to have my geoinfos private and my properties public

thanks in advance for your help


Solution

  • You've made the properties private. If you want them to be public try:

    public List<GeoInfo> GeoInfos { get; set; }
    

    The auto-implemented value that is stored locally in the object will be private; but the properties themselves are public.

    Because what you are declaring there are the property accessors.

    If you want to write everything explicitly, you could do it the old pre 3.0 way

    private List<GeoInfo> geoInfos = new List<GeoInfo>;
    public List<GeoInfo> GeoInfos {
      get { return geoInfos; }
      set { geoInfos = value; }
    }
    

    This still relies on geoInfos being initialized somewhere (like the constructor) -- or nullPointerException will return.

    You could do lazy-evaluation on it right in the getter:

    private List<GeoInfo> geoInfos = new List<GeoInfo>;
    public List<GeoInfo> GeoInfos {
      get { if (geoInfos == null) {
              geoInfos = new List<GeoInfo>;
            } 
            return geoInfos; 
          }
      set { geoInfos = value; }
    }
    

    This ensures that you don't have to specify a call in the constructor, and you don't have to worry about the execution sequence setting the element explicitly prior to getting it.

    But if you use the auto-generated-properties, you will have to explicitly set the reference at some point. AS suggested elsewhere, the best bet is the constructor.