0

This may have been asked many times, and I've been searching around, but for some reason, this doesn't make sense to me. So it seems like I create a new instance, but Visual studio tells me that Object reference not set to an instance of an object.

public class Test{
   private Dictionary<string, Service> serviceList;
   private void GetList(string ID){
       foreach(var service in Service.Load()){
            servicelist.Add(service.ID, new Service());
       }
   }
}

I think when I use new Service(), I basically create a new instance of the Service every single time I move to the next element in the Dictionary? Service is a class

Test
  • 87
  • 4
  • 12
  • 1
    Yes, you do. Please consider reading: http://msdn.microsoft.com/en-us/library/fa0ab757.aspx, http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx. – BartoszKP Jun 20 '14 at 17:22
  • Well, a new one gets created for each service in service.Load and is *added* to the dictionary. I'm not sure what you mean by "Move to the next element". So, what is your question exactly? Just that a new instance is created? – BradleyDotNET Jun 20 '14 at 17:24
  • yeah I read that before, but not sure why I get the error that I posted above. I forgot to include it – Test Jun 20 '14 at 17:24
  • yes you are right a new instance will be created each iteration and a reference will stored in dictionary – BRAHIM Kamel Jun 20 '14 at 17:24
  • 4
    you don't initialize `serviceList` – L.B Jun 20 '14 at 17:24
  • http://msdn.microsoft.com/en-us/library/fa0ab757.aspx – Dennis_E Jun 20 '14 at 17:25
  • so Service.Load() is actually an IEnumerable interface, so basically foreach will iterate through IEnumerable and then add a new Service associated with the ID? – Test Jun 20 '14 at 17:25
  • Regarding your updated question, please read: http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – BartoszKP Jun 20 '14 at 17:25

3 Answers3

2

You forgot to instantiate your list, you need:

private Dictionary<string, Service> serviceList = new Dictionary<string, Service>();
   private void GetList(string ID){
    ....

To answer your initial question: Yes, a new instance is created for each item in the collection being iterated over.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

you are just declaring the dictionary you need to initialize it

do this

private Dictionary<string, Service> serviceList = new  Dictionary<string, Service>();
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47
0

Yes. That exactly you do. When you call new Service () you create a new instance of the class, except if Service is a singleton class

CodeArtist
  • 5,534
  • 8
  • 40
  • 65