I'm confused about why this object is null

  • Thread starter SlurrerOfSpeech
  • Start date
  • Tags
    Confused
In summary, the conversation involved a discussion about a class called FriendList, which contains a dictionary of names and a timestamp. One of the methods in the class, PrintInfo(), prints out the names and timestamp. The conversation then shifted to a problem encountered when using the class in a procedure called BuildFriendHistory(). The error was a NullReferenceException, and it was determined that either flist or flist.names was null. The solution was to add a constructor for FriendList objects and initialize this.names with a new Dictionary<string, int>. The conversation also touched on the implicit initialization of data members in C# constructors.
  • #1
SlurrerOfSpeech
141
11
I have a class like

Code:
    public class FriendList
    {
        public Dictionary<string, int> names { get; set; } // List of friends names and number of occurrences (in case two or more friends have the same name)
        public DateTime timestamp { get; set; } // date/time on the data file

        public static FriendList operator / ( FriendList first, FriendList second )
        {
            // Returns a FriendList of every friend in first but not second, with the timestamp
            // of the returned object being an arbitrary value. 
            FriendList firstNotSecond = new FriendList();
            foreach ( KeyValuePair<string,int> thisName in first.names  )
            {
                int secondNum = second.names.ContainsKey(thisName.Key) ? second.names[thisName.Key] : 0;
                if ( thisName.Value > secondNum )
                {
                    firstNotSecond.names[thisName.Key] = thisName.Value - secondNum;
                }
            }
            return firstNotSecond;          
        }

        public void PrintInfo ( )
        {
            Console.WriteLine("Friends from list timestamped with {0}", this.timestamp.ToString());
            foreach ( KeyValuePair<string, int> thisFriend in this.names )
            {
                Console.WriteLine("\t\t{0} ({1})", thisFriend.Key, thisFriend.Value);
            }
        }

        public int CountFriends ( )
        {
            int count = 0;
            foreach ( KeyValuePair<string, int> namein this.names )
            {
                count += name.Value;
            }
            return count;
        }

    }

but when I use that class in the following procedure

Code:
        private void BuildFriendHistory ( )
        {
            // Takes all text files currently in the Data folder
            // and extracts their friends lists into a List<FriendList>.
            // Prints any error encountered along the way.
            this._fhist = new List<FriendList>();
            foreach ( string thisFilePath in Directory.GetFiles(this._datadir) )
            {
                FriendList flist = new FriendList();
                string line;
                System.IO.StreamReader file = new System.IO.StreamReader(thisFilePath);
                while ( (line = file.ReadLine()) != null )
                {
                    int k = line.LastIndexOf(' ');
                    flist.names[line.Substring(0, k)] = Int32.Parse(line.Substring(k + 1));
                }
                this._fhist.Add(flist);
            }
        }

I'm getting a NullReferenceException on the line

Code:
flist.names[line.Substring(0, k)] = Int32.Parse(line.Substring(k + 1))

and I know (because I've stepped through and checked) that

Code:
line.Substring(0, k)

and

Code:
Int32.Parse(line.Substring(k + 1))

are not NULL. Therefore NULL is some part of

Code:
flist.names

and I'm wondering if you can help me figure out why.
 
Technology news on Phys.org
  • #2
Mods, you can remove this thread. I figured out my problem (Needed to create a constructor for FriendList objects and in that constructor intialize this.names = new Doctionary<string,int> () )
 
  • #3
C:
while ( (line = file.ReadLine()) != null )
{
      int k = line.LastIndexOf(' ');
      flist.names[line.Substring(0, k)] = Int32.Parse(line.Substring(k + 1));
}
this._fhist.Add(flist);
Either flist is null or flist.names is null. Before drilling down to flist.names[line.Substring(0, k)], you should do some sanity check to make sure that neither of this is null. Nowhere in the code you posted did I see anything where flist is initialized, which you're probably already figured out.

BTW, just because a problem gets solved, we don't automatically delete a thread.
 
  • #4
Mark44 said:
Either flist is null or flist.names is null. Before drilling down to flist.names[line.Substring(0, k)], you should do some sanity check to make sure that neither of this is null. Nowhere in the code you posted did I see anything where flist is initialized, which you're probably already figured out.

I thought that if you have a class like

Code:
public class MyClass
{
    SomeType MyField1 { get; set; }
    SomeOtherType MyField2 { get; set; }
}

then both fields are implicitely newed when creating a new MyClass.
 
  • #5
SlurrerOfSpeech said:
I thought that if you have a class like

Code:
public class MyClass
{
    SomeType MyField1 { get; set; }
    SomeOtherType MyField2 { get; set; }
}

then both fields are implicitely newed when creating a new MyClass.
Your code is C#, right? Assuming you have a constructor for MyClass, space is allocated for the data members of MyClass, but unless the constructor initializes these members explicitly they wil be initialized to 0 in some form, for numbers, and null if they are objects of some kind.
 
  • #6
Mark44 said:
Your code is C#, right? Assuming you have a constructor for MyClass, space is allocated for the data members of MyClass, but unless the constructor initializes these members explicitly they wil be initialized to 0 in some form, for numbers, and null if they are objects of some kind.

Got it. Thanks!
 

Related to I'm confused about why this object is null

1. Why is the object null?

The object is null because it does not have a value assigned to it. This could be due to a coding error or because the object was never initialized.

2. How do I fix a null object?

To fix a null object, you need to assign a value to it. This can be done by initializing the object or reassigning a value to it.

3. What causes an object to be null?

An object can be null if it was never initialized or if it was explicitly set to null by the code. It can also happen when trying to access an object that doesn't exist or has been deleted.

4. Can a null object be used in code?

No, a null object cannot be used in code as it does not have a value. Attempting to use a null object will result in an error.

5. How can I prevent null objects in my code?

To prevent null objects, it is important to properly initialize variables and objects before using them. It is also helpful to check for null values before using an object in code.

Similar threads

  • Programming and Computer Science
Replies
2
Views
847
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
4
Views
910
  • Programming and Computer Science
Replies
9
Views
1K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
9
Views
2K
  • Programming and Computer Science
Replies
3
Views
945
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
1
Views
960
Back
Top