-6

I am not sure if my question makes sense. But I am just wondering if there is a difference between these two lines of code:

Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>();

vs

Dictionary<int, List<string>> myDictionary = null;

I know the first line instatiates a new dictionary object but since I haven't added anything into the dictionary, it's just an empty object. The second line is just an empty dictionary object. Is there a difference?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
d1du
  • 296
  • 1
  • 3
  • 12
  • You could use your debugger and find out by yourself?!? – Uwe Keim Jul 11 '16 at 05:56
  • 1
    Null points to no object. Here we see some information and facts about the null literal ("null"). Null is represented by the value 0, but you cannot use 0 instead of null in your programs. Null causes lots of exceptions. – Gehan Fernando Jul 11 '16 at 06:02
  • Try calling `.Count` on both - you'll see the difference soon enough! – CompuChip Jul 11 '16 at 06:03
  • Possible duplicate of [What is null in Java?](http://stackoverflow.com/questions/2707322/what-is-null-in-java) OR [What is null in c#, java?](http://stackoverflow.com/questions/2028298/what-is-null-in-c-java) – Draken Jul 11 '16 at 06:08
  • Thank you for all nontroll responses. Downvoters, get a lyfe pl0x. – d1du Oct 07 '16 at 21:34

6 Answers6

3

In first case:

     Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>();
     myDictionary.Add(key,value); // NOT throw null reference exception.

In second case:

     Dictionary<int, List<string>> myDictionary = null;
     myDictionary.Add(key,value); // will throw null reference exception.

In order to use any collection object, you would need to create placeholder first.

Gaurava Agarwal
  • 974
  • 1
  • 9
  • 32
  • 4
    I suggest you change your examples to ones that would compile - and use C# terminology rather than Java terminology (null *reference* exception, not null *pointer* exception) – Jon Skeet Jul 11 '16 at 06:07
2

Think of it as the following:

The variable is an empty paper. You may or may not write an address on it that leads you to some location.

The first line writes on the paper an address to the object (created after the new keyword).

On the second line, you just have an empty paper that is expected (by the compiler) to hold a dictionary reference at some point, but currently it is just an empty paper. So if you try to use it to go to the dictionary address, you can't (aka NullReferenceException). There is no information about where the object is (there is no address actually).

In Code:

Dictionary<int, List<string>> myDictionary = new Dictionary<int, List<string>>();
myDictionary.Add(1, "1"); // OK, myDictionary points to an address of
                         // Dictionary object and I can access it.

While:

Dictionary<int, List<string>> myDictionary = null;
myDictionary.Add(1, "1");  // Fails at run-time, I have no address for a Dictionary object 
                           // here AKA : NullReferenceException

Wrong statements you said:

You're not declaring a class null as you said, you're creating a variable pointing to null.

The second line is not an empty dictionary object as you said. It is a variable of type Dictionary that points to NULL. There is no empty dictionary object in memory.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
1

Simple Answer, First case you can use it, Second case will give you NullReferenceException while you proceed with that, Because null means not existing So you cannot access it until it is instantiated.

There is nothing Wrong with the second declaration, but If you want to use this means you need to instantiate them(before use), Otherwise it will Throws NullReferenceException. Let PopulateDictonary() will be a method which will Return a Dictionary object then You can use this method to instantiate the myDictionary.

That is:

Dictionary<int, List<string>> myDictionary;
// Some code here, Not using myDictionary
myDictionary = PopulateDictonary();

Note :- You should check for Null before useing the myDictionary if you go with conditionaly Instantiate the object to avoid Exception.

Community
  • 1
  • 1
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • It's called `NullReferenceException`. – Uwe Keim Jul 11 '16 at 05:56
  • I was going to write the same. I can add to this answer that the first one you are instantiating, and in the second one you are only declaring it. For use it, you must instantiate, not only declare. – matiaslauriti Jul 11 '16 at 05:56
  • 2
    This doesn't really explain the difference clearly. Maybe the variable will be assigned a different value later on... maybe it will be assigned a value *conditionally*... and using the `null` reference may be fine. For example, it may be passed as an argument to another method which can handle a `null` parameter value. `NullReferenceException` will only be thrown if code tries to dereference the value. – Jon Skeet Jul 11 '16 at 05:57
  • @JonSkeet : let me explain – sujith karivelil Jul 11 '16 at 05:58
  • I would remove anything about default values - that's irrelevant if this is a local variable declaration. And again, the variable can be "used" in terms of passing the value on to something else, while still having a null value. – Jon Skeet Jul 11 '16 at 06:06
  • @JonSkeet : thanks for the valuable suggestions and support – sujith karivelil Jul 11 '16 at 06:16
1

The first line actually creates an object (memory is allocated); this means you have something to reference and act upon (for example, myDictionary.Count() will return 0). The code if (null == myDictionary) will evaluate to false.

The second line creates no object; you have a reference to nothing (and in this case, calling myDictionary.Count() will result in a NullReferenceException being thrown). The code if (null == myDictionary) will evaluate to true.

1

The second line is not an empty dictionary object. Try adding stuff to the 2nd dictionary object to find out yourself. Generally you point a reference to null when you actually want to assign an object to that reference later in the program.

Geek
  • 23,089
  • 20
  • 71
  • 85
1

There are many differences between the two statements, the most basic one: the first is an initialization while the latter is just a declaration. Consider the following code:

Base b = new Derived();

Towards

Base b = null;

In the first statement you create a new instance of Derived and assign it to b. Usually you need an instance of a class to call its members (for simplicity we omit the static members here), in your case the Add-method defined in Dictionary for example. By a declaration you simply define the members you may call on an instance of a class, however there is nothing said about that instance on which you call those members. So basically you need two information: the code-contract which is defined by the interface (not the OOP-meaning) you use - in your case this is just Dictionary<int, List<string>>. Now you know what you can do with an instance of this class. However you don´t have an instance of the class as long as you use the null-assignement. This is the second information - the actual instance.

To stay in my previous example how should the compiler actally know which class you actually use - Base or Derived. This will not neccessarily affect what you can do with the instance (which is given by the definition within Base), but moreover how you do it as Derived may have its own logic for doing things defined in Base.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111