Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hey all I am trying to add some values to a list that's within my class constructor.

Issue being is that it does not seem to want to add a string (even though its defined as one) to the list.

This is my current code:

namespace laptopWatcher
{
   public partial class clockCountDown : Window
   {
       public class networkDetails
       {
           public string _ip { get; set; }
           public string _subnetMask { get; set; }
           public string _defaultGateway { get; set; }
           public string _machineName { get; set; }
           public string _hostName { get; set; }
           public string _userName { get; set; }
           public string _userDomainName { get; set; }
           public List<string> _userNames { get; set; }
       }

       private void getUserNames()
       {            
           SelectQuery query = new SelectQuery("Win32_UserAccount");
           ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
           List<string> _tmp = new List<string>();

           foreach (ManagementObject envVar in searcher.Get())
           {
               Console.WriteLine(envVar["Name"].ToString());
               _tmp.Add(envVar["Name"].ToString());
               //theNetwork._userNames.Add(envVar["Name"].ToString());
           }

           theNetwork._userNames.AddRange(_tmp);
       }
   }    
}

The error I am getting is:

System.NullReferenceException: 'Object reference not set to an instance of an object.' laptopWatcher.clockCountDown.networkDetails._userNames.get returned null.

This error is on this line:

theNetwork._userNames.AddRange(_tmp);

That seems correct to me? Odvesley I am missing something or not doing this in the correct order?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

just do it

theNetwork._userNames = new List<string>(_tmp);

and read this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...