C# FAQ: What does Object reference not set to an instance of an object mean

Jump to: navigation, search


What does "Object reference not set to an instance of an object" mean?

Almost every day, beginning C# programmers ask:
Why do I get the error "Object reference not set to an instance of an object"?

The reason is that the program is trying to access a member of a reference type variable which is set to null.

A simple example

The situation which causes this error message may not be so obvious as in the this simple example: The variable being referenced could be a class field, a parameter, or a local variable which had been instantiated but was later set to null. Nevertheless, here is a simple source code example that illustrates the problem:

using System;
class Problem 
   static void Main()
      Problem problem = null; // problem has not been instantiated
      // ...
   public int ProblemProperty
      get { return 0; }
   public string ProblemMethod() 
      return null;

In the Main method, notice that problem is set to null. Therefore, the following code will throw a NullReferenceException:

   // problem is null, and ProblemProperty cannot be called
   // on a null reference
   int prop = problem.ProblemProperty;
catch (NullReferenceException nre)
       "Cannot read ProblemProperty, problem is null.\n" + 

Since problem is null, it has no members to be accessed. Whereas the preceding example used a property call, the following example source code uses a method call:

   // problem is null, and ProblemMethod cannot be called
   // on a null reference
catch (NullReferenceException nre)
      "Cannot call ProblemMethod(), problem is null.\n" + 

The preceding code will throw a NullReferenceException; because, problem is still null. It is irrelevant that the first example call was a property and the second was a method: they are both members of the type.

To solve this problem, be sure the problem object is instantiated before being referenced. The following sample source code instantiates problem and, so, avoids the error message:

Problem problem = new Problem();    // instantiate problem
int prop = problem.ProblemProperty; // making member access possible 

Now, problem contains a reference to an instance of Problem; so, any of its members can be called.

A more complex example

Many null reference problems are more difficult to diagnose and solve than this simple example. Sometimes there are multiple levels of indirection, making diagnosis more difficult.

In this example, assume problem references an object, but there is still an error in the following sample source code:

   // still causes error because ProblemMethod() 
   // returns null, Trim() cannot be called on null.
catch (NullReferenceException nre)
      "Cannot call Trim(), ProblemMethod() returns null.\n" + 

An error occurs in the preceding code, because ProblemMethod returns null. Accordingly, the code is trying to call the Trim method on a string reference that is set to null.

The best way to fix such a problem is to debug ProblemMethod to determine the reason null is returned.

In the preceding example, ProblemMethod should not return null. If null were a valid return value for ProblemMethod, then it would be necessary to check the ProblemMethod return value before calling any members of the return value type. For example:

if (problem.ProblemMethod() != null)
   // return value is non-null

More CSharp Language FAQs

Go to Visual CSharp FAQ (main page).

Consider these related Frequently Asked Questions—FAQs:

  1. Are C# constructors inherited?
  2. Are C# parameters passed by reference or by value ?
  3. Can a property have different get and set access?
  4. Can const and static be used together?
  5. Can I directly call a native function exported from a DLL?
  6. Do unused references to external assemblies lead to code bloat?
  7. Does C# have its own class library?
  8. Does C# have macros or a preprocessor?
  9. Does C# support custom exceptions?
  10. Does C# support jagged arrays?
  11. Does C# support variable method arguments (vararg)?
  12. How call overloaded operators from non-supporting languages?
  13. How can I force garbage collection?
  14. How can I output simple debugging messages?
  15. How can one constructor call another?
  16. How check the object type at runtime?
  17. How can type name clashes be resolved?
  18. How do destructors work in C#?
  19. How do I declare an out variable?
  20. How do I get DllImport to work?
  21. How do I make a C# DLL?
  22. How do I use trace and assert?
  23. How get the type name at runtime?
  24. How keep a local variable in scope across a try-catch block?
  25. How make sure C# classes will interoperate with other .NET languages?
  26. How perform a case insensitive string comparison?
  27. How process command line arguments?
  28. How specify a C# literal type?
  29. How subscribe to events exposed by remoted objects?
  30. How to obtain type information on the fly using typeof?
  31. How use an alias for a class or namespace?
  32. How would I create a Delegate or MulticastDelegate?
  33. Is there C# support for C-type macros?
  34. Is there C# support for templates?
  35. What are the C# character escape sequences (\)?
  36. What does at sign (@) identifier mean?
  37. What does "Object reference not set to an instance of an object" mean?
  38. What is a namespace?
  39. What is a type alias?
  40. What is C#?
  41. What is a C# response file?
  42. What is a verbatim string literal (@)?
  43. What is the C# Language Specification?
  44. What is the #define preprocessor directive?
  45. What is the difference between const and static readonly?
  46. What is the difference between delegate and event?
  47. What is the difference between GetType() and typeof?
  48. What is the difference between new and override?
  49. What is the difference between the out and ref parameter modifiers?
  50. What is the difference between string and System.String?
  51. What is the difference between using a cast and the as operator?
  52. What is the syntax for calling an overloaded constructor from within a constructor?
  53. What is the use of the C# compiler's /target: command line option?
  54. What is the Windows Class Viewer?
  55. What software is needed to develop C# applications?
  56. When should an exception be thrown?
  57. When should Equals and == be used?
  58. Will Console.WriteLine() stop printing upon encountering a NULL character in a string?
  59. Why add a using statement and a reference?
  60. Why are hashtable lookups so slow with struct keys?
  61. Why do I get a syntax error when I try to declare a variable named checked?
  62. Why does C# not support checked exceptions?
  63. Why does my Windows application open a console window each time it is run?
  64. Why doesn't the C# switch statement work like I expect it to?
  65. Why doesn't a Windows Form project use visual styles in XP?
  66. Why get an error (CS1006) when declaring a method without a return type?
  67. Why must struct constructors have at least one argument?
C# Online.NET