c# - what is a nullreferenceexception and how do i fix it_ - stack overflow

31
community wiki John Saunders 18 Answers active oldest votes 718 163 I have some code and when it executes, it throws a NullReferenceException , saying: Object reference not set to an instance of an object. What does this mean, and what can I do about it? c# .net vb.net null nullreferenceexception share improve this question edited Jan 12 at 16:12 1 in case framework based error refer my below answer stackoverflow.com/questions/779091/… Vijay Kumbhoje Dec 17 '14 at 7:17 778 What is the cause? Bottom Line You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null , or you never set it to anything at all. Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A". The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException . More Specifically The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was initialized, but is no longer initialized). This means the reference is null , and you cannot access members through a null reference. The simplest case: string foo = null; foo.ToUpper(); This will throw a NullReferenceException at the second line, because you can't call the instance method ToUpper() on a string reference pointing to null . Debugging How do you find the source of a NullReferenceException ? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual What is a NullReferenceException and how do I fix it? add a comment

Upload: herikz

Post on 15-Dec-2015

14 views

Category:

Documents


2 download

DESCRIPTION

nullreferenceexception c# stackoverflow

TRANSCRIPT

Page 1: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiJohn Saunders

18 Answers active oldest votes

718

163

I have some code and when it executes, it throws a NullReferenceException , saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do about it?

c# .net vb.net null nullreferenceexception

share improve this question edited Jan 12 at 16:12

1 in case framework based error refer my below answer stackoverflow.com/questions/779091/… – Vijay Kumbhoje Dec 17 '14 at 7:17

778

What is the cause?

Bottom Line

You are trying to use something that is null (or Nothing in VB.NET). This means you either set itto null , or you never set it to anything at all.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B"passed a null to method "A".

The rest of this article goes into more detail and shows mistakes that many programmers often makewhich can lead to a NullReferenceException .

More Specifically

The runtime throwing a NullReferenceException always means the same thing: you are trying to usea reference. The reference is not initialized (or it was initialized, but is no longer initialized).

This means the reference is null , and you cannot access members through a null reference. Thesimplest case:

string foo = null;foo.ToUpper();

This will throw a NullReferenceException at the second line, because you can't call the instancemethod ToUpper() on a string reference pointing to null .

Debugging

How do you find the source of a NullReferenceException ? Apart from looking at the exception itself,which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual

What is a NullReferenceException and how do I fix it?

add a comment

Page 2: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouseover their names, opening a (Quick)Watch window or using the various debugging panels like Localsand Autos.

If you want to find out where the reference is or isn't set, right­click its name and select "Find AllReferences". You can then place a breakpoint at every found location and run your program with thedebugger attached. Every time the debugger breaks on such a breakpoint, you need to determinewhether you expect the reference to be non­null, inspect the variable and and verify that it points to aninstance when you expect it to.

By following the program flow this way you can find the location where the instance should not be null,and why it isn't properly set.

Examples

Some common scenarios where the exception can be thrown:

Generic

ref1.ref2.ref3.member

If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException . If you want to solve theproblem, then find out which one is null by rewriting the expression to its simpler equivalent:

var r1 = ref1;var r2 = r1.ref2;var r3 = r2.ref3;r3.member

Specifically, in HttpContext.Current.User.Identity.Name , the HttpContext.Current could be null,or the User property could be null, or the Identity property could be null.

Indirect

public class Person public int Age get; set; public class Book public Person Author get; set; public class Example public void Foo() Book b1 = new Book(); int authorAge = b1.Author.Age; // You never initialized the Author property. // there is no Person to get an Age from.

The same applies to nested object initializers:

Book b1 = new Book Author = Age = 45 ;

While the new keyword is used, it only creates a new instance of Book , but not a new instanceof Person , so the Author the property is still null .

Array

int[] numbers = null;int n = numbers[0]; // numbers is null. There is no array to index.

Page 3: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Array Elements

Person[] people = new Person[5];people[0].Age = 20 // people[0] is null. The array was allocated but not // initialized. There is no Person to set the Age for.

Jagged Arrays

long[][] array = new long[1][];array[0][0] = 3; // is null because only the first dimension is yet initialized. // Use array[0] = new long[2]; first.

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;int age = agesForNames["Bob"]; // agesForNames is null. // There is no Dictionary to perform the lookup.

Range Variable (Indirect/Deferred)

public class Person public string Name get; set; var people = new List<Person>();people.Add(null);var names = from p in people select p.Name;string firstName = names.First(); // Exception is thrown here, but actually occurs // on the line above. "p" is null because the // first element we added to the list is null.

Events

public class Demo public event EventHandler StateChanged;

protected virtual void OnStateChanged(EventArgs e) StateChanged(this, e); // Exception is thrown here // if no event handlers have been attached // to StateChanged event

Bad Naming Conventions:

If you named fields differently from locals, you might have realized that you never initialized the field.

public class Form1 private Customer customer;

private void Form1_Load(object sender, EventArgs e) Customer customer = new Customer(); customer.Name = "John";

private void Button_Click(object sender, EventArgs e) MessageBox.Show(customer.Name);

Page 4: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

This can be solved by following the convention to prefix fields with an underscore:

private Customer _customer;

ASP.NET Page Life cycle:

public partial class Issues_Edit : System.Web.UI.Page protected TestIssue myIssue;

protected void Page_Load(object sender, EventArgs e) if (!IsPostBack) // Only called on first load, not when button clicked myIssue = new TestIssue();

protected void SaveButton_Click(object sender, EventArgs e) myIssue.Entry = "NullReferenceException here!";

ASP.NET Session Values

// if the "FirstName" session value has not yet been set,// then this line will throw a NullReferenceExceptionstring firstName = Session["FirstName"].ToString();

ASP.NET MVC empty view models

When you return an empty model (or model property) from your controller, the exception occurs whenthe views accesses it:

// Controllerpublic class Restaurant:Controller public ActionResult Search() return View(); // Forgot the provide a Model here.

// Razor view @foreach (var restaurantSearch in Model.RestaurantSearch) // Throws.

WPF Control Creation Order and Events

WPF controls are created during the call to InitializeComponent in the order they appear in thevisual tree. A NullReferenceException will be raised in the case of early­created controls with eventhandlers, etc, that fire during InitializeComponent which reference late­created controls.

For example :

Page 5: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

<Grid> <!‐‐ Combobox declared first ‐‐> <ComboBox Height="23" HorizontalAlignment="Left" Margin="56,57,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" SelectedIndex="0" SelectionChanged="comboBox1_SelectionChanged"> <ComboBoxItem Content="Item 1" /> <ComboBoxItem Content="Item 2" /> <ComboBoxItem Content="Item 3" /> </ComboBox>

<!‐‐ Label Declared later ‐‐> <Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="56,23,0,0" Name="label1" VerticalAlignment="Top" /></Grid>

Here comboBox1 is created before label1 . If comboBox1_SelectionChanged attempts toreference label1 it will not yet have been created.

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!

Changing the order of the declarations in the XAML (ie: listing label1 before comboBox1 , ignoringissues of design philosophy, would at least resolve the NullReferenceException here.

Ways to Avoid

Explicitly check for null , and ignore null values.

If you expect the reference sometimes to be null, you can check for it being null before accessinginstance members:

void PrintName(Person p) if (p != null) Console.WriteLine(p.Name);

Explicitly check for null , and provide a default value.

Methods calls you expect to return an instance can return null , for example when the object beingsought cannot be found. You can choose to return a default value when this is the case:

string GetCategory(Book b) if (b == null) return "Unknown"; return b.Category;

Explicitly check for null from method calls and throw a custom exception.

Page 6: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

You can also throw a custom exception, only to catch it in the calling code:

string GetCategory(string bookTitle) var book = library.FindBook(bookTitle); // This may return null if (book == null) throw new BookNotFoundException(bookTitle); // Your custom exception return book.Category;

Use Debug.Assert if a value should never be null , to catch the problem earlierthan the exception occurs.

When you know during development that a method maybe can, but actually never shouldreturn null , you can use Debug.Assert() to break as soon as possible when it does occur:

string GetTitle(int knownBookID) // You know this should never return null. var book = library.GetBook(knownBookID);

// Exception will occur on the next line instead of at the end of this method. Debug.Assert(book != null, "Library didn't return a book for known book ID.");

// Some other code ...

return book.Title; // Will never throw NullReferenceException in Debug mode.

Though this check will not end up in your release build, causing it to throwthe NullReferenceException again when book == null at runtime in release mode.

Use GetValueOrDefault() for nullable value types to provide a default value whenthey are null .

DateTime? appointment = null;Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));// Will display the default value provided, because appointment is null.

appointment = new DateTime(2022, 10, 20);Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));// Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

The shorthand to providing a default value when a null is encountered:

IService CreateService(ILogger log, Int32? frobPowerLevel) var serviceImpl = new MyService(log ?? NullLog.Instance);

// Note that the above "GetValueOrDefault()" can also be rewritten to use // the coalesce operator: serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;

Use the null condition operator: ?. (available in C# 6 and VB.NET 14):

This is also sometimes called the safe navigation operator. If the expression on the left side of theoperator is null, then the right side will not be evaluated and null is returned instead. That means caseslike this:

Page 7: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wiki26 revs, 14 users 28%John Saunders

var title = person.Title.ToUpper();

If the person does not have a title, this will throw an exception because it is trying to call ToUpper ona property with a null value.

In C# 5 and below, this can be guarded with:

var title = person.Title == null ? null : person.Title.ToUpper();

Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax forthis:

var title = person.Title?.ToUpper();

This will result in the title variable being null, and the call to ToUpper is not made if person.Title isnull.

Of course, you still have to check title for null!

int titleLength = 0;if (title != null) titleLength = title.Length; // If title is null, this would throw NullReferenceException

share improve this answer edited Aug 5 at 17:07

8 Maybe this is a dumb comment but wouldnt the first and best way to avoid this problem be to initialize theobject? For me if this error occurs it is usually because I forgot to initialize something like the array element.I think it is far less common to define the object as null and then reference it. Maybe give the way to solveeach problem adjacent to the description. Still a good post. – JPK May 20 '14 at 6:39

9 What if there is no object, but rather the return value from a method or property? – John Saunders May 20'14 at 6:41

1 The book/author example is a little weird.... How does that even compile? How does intellisense even work?What is this I'm not good with computar... – Will Sep 8 '14 at 18:26

2 @Will: does my last edit help? If not, then please be more explicit about what you see as a problem. – John Saunders Sep 8 '14 at 18:41

2 @JohnSaunders Oh, no, sorry, I meant the object initializer version of that. new Book Author = Age= 45 ; How does the inner initialization even... I can't think of a situation where inner init would everwork, yet it compiles and intellisense works... Unless for structs? – Will Sep 8 '14 at 18:44

@Will: interesting. I'm not sure exactly which syntax that is (I didn't write that example), but ReSharper saysthat it's equivalent to ` Book b1 = new Book(); b1.Author.Age = 45; `, which is clearly a problem. – John Saunders Sep 8 '14 at 19:45

I checked­­the syntax is valid for objects, but not for a struct property. Does work if you initialize Author.Freaky. – Will Sep 8 '14 at 20:23

@Will: you mean valid for classes but not for structs. Struct instances are are objects too. – John Saunders Sep 8 '14 at 20:32

References don't "point to null". They have a value of null, which conceptually doesn't point anywhere. Onolder, real­mode systems, null pointed to address zero. But on modern processors, addresses are virtualizardand zero would normally be an invalid address. – Jonathan Wood Dec 31 '14 at 1:42

My favourite cause of null reference exceptions is the incorrect use of the "As" cast operator. You shouldnever use this without a null check. If you are certain about the type, use a normal cast, and if you are wrongyou'll get an InvalidCastException. – Dominic Cronin Jan 30 at 8:25

Page 8: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiSimon Mourier

@JonathanWood they actually do, and you get an Access Violation under the hood that gets turned intoNullReferenceException, which is why these are really nasty. – Yishai Galatzer Jun 6 at 2:16

83

Another scenario is when you cast a null object into a value type. For example, the code below:

object o = null; DateTime d = (DateTime)o;

It will throw a NullReferenceException on the cast. It seems quite obvious in the above sample, butthis can happen in more "late­binding" intricate scenarios where the null object has been returned fromsome code you don't own, and the cast is for example generated by some automatic system.

One example of this is this simple ASP.NET binding fragment with the Calendar control:

<asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />

Here, SelectedDate is in fact a property ­ of DateTime type ­ of the Calendar Web Control type,and the binding could perfectly return something null. The implicit ASP.NET Generator will create apiece of code that will be equivalent to the cast code above. And this will raisea NullReferenceException that is quite difficult to spot, because it lies in ASP.NET generated codewhich compiles fine...

share improve this answer edited May 25 at 12:30

Great catch. One­liner way to avoid: DateTime x = (DateTime) o as DateTime? ?? defaultValue; – Serge Shultz Jun 29 at 11:07

74

NullReference Exception ­­ Visual Basic

The NullReference Exception for Visual Basic is no different from the one in C#. After all, they areboth reporting the same exception defined in the .NET Framework which they both use. Causesunique to Visual Basic are rare (perhaps only one).

This answer will use Visual Basic terms, syntax and context. The examples used come from a largenumber of past Stack Overflow questions. This is to maximize relevance by using the kinds ofsituations often seen in posts. A bit more explanation is also provided for those who might need it. Anexample similar to yours is very likely listed here.

Note:

1. This is concept­based: there is no code for you to paste into your project. It is intended to helpyou understand what causes a NullReferenceException (NRE), how to find it, how to fix it, andhow to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.

2. The examples (from Stack Overflow posts) do not always show the best way to do something inthe first place.

3. Typically, the simplest remedy is used.

Basic Meaning

add a comment

add a comment

Page 9: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

The message "Object not set to instance of Object" means you are trying to use an object which hasnot been initialized. This boils down to one of these:

Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate'it)

Something which your code assumed would initialize an object, did not

Possibly, other code prematurely invalidated an object still in use

Finding The Cause

Since the problem is an object reference which is Nothing , the answer is to examine them to find outwhich one. Then determine why it is not initialized. Hold the mouse over the various variables andVisual Studio (VS) will show their values ­ the culprit will be Nothing .

You should also remove any Try/Catch blocks from the relevant code, especially ones where there isnothing in the Catch block. This will cause your code to crash when it tries to use an object which isNothing. This is what you want, because it will identify the exact location of the problem, and allowyou to identify the object causing it.

A MsgBox in the Catch which displays Error while... will be of little help. This method also leadstovery bad Stack Overflow questions, because the you can't describe the actual exception, the objectinvolved or even the line of code where it happens.

You can also use the Locals Window (Debug ­> Windows ­> Locals) to examine your objects.

Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting anew question.

See also:

Breakpoints

MSDN: How to: Use the Try/Catch Block to Catch Exceptions

MSDN: Best Practices for Exceptions

Examples and Remedies

Class Objects / Creating an Instance

Dim reg As CashRegister...TextBox1.Text = reg.Amount ' NRE

The problem is that Dim does not create a CashRegister object; it only declares a variablenamed reg of that Type. Declaring an object variable and creating an instance are two differentthings.

Page 10: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Remedy

The New operator can often be used to create the instance when you declare it:

Dim reg As New CashRegister ' [New] creates instance, invokes the constructor

' Longer, more explicit form:Dim reg As CashRegister = New CashRegister

When it is only appropriate to create the instance later:

Private reg As CashRegister ' Declare ...reg = New CashRegister() ' Create instance

Note: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister'...

Public Sub New() '... Dim reg As New CashRegisterEnd Sub

This will create a local variable, reg , which exists only in that context (sub). The reg variable withmodule level Scope which you will use everywhere else remains Nothing .

Missing the New operator is the #1 cause of NullReference Exceptions seen in theStack Overflow questions reviewed.

Visual Basic tries to make the process clear repeatedly using New : Using the New Operatorcreates a new object and calls Sub New ­­ the constructor ­­ where your object can perform anyother initialization.

To be clear, Dim (or Private ) only declares a variable and its Type . The Scope of the variable ­whether it exists for the entire module/class or is local to a procedure ­ is determined by where it isdeclared. Private | Friend | Public defines the access level, not Scope.

For more information, see:

New Operator

Scope in Visual Basic

Access Levels in Visual Basic

Value Types and Reference Types

Arrays

Arrays must also be instantiated:

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Page 11: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Private arr as String() = New String(10)' orPrivate arr() As String = New String(10)

' For a local array (in a procedure) and using 'Option Infer':Dim arr = New String(10)

Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer , the As <Type> and New elements are optional:

Dim myDbl As Double() = 1.5, 2, 9.9, 18, 3.14Dim myDbl = New Double() 1.5, 2, 9.9, 18, 3.14Dim myDbl() = 1.5, 2, 9.9, 18, 3.14

The data Type and array size are inferred from the data being assigned. Class/Module leveldeclarations still require As <Type> with Option Strict :

Private myDoubles As Double() = 1.5, 2, 9.9, 18, 3.14

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count ‐ 1 arrFoo(i).Bar = i * 10 ' ExceptionNext

The array has been created, but the Foo objects in it have not.

Remedy

For i As Integer = 0 To arrFoo.Count ‐ 1 arrFoo(i) = New Foo() ' Create Foo instance arrFoo(i).Bar = i * 10Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo) ' List created, but it is emptyDim f As Foo ' Temporary variable for the loop

For i As Integer = 0 To 5 f = New Foo() ' Foo instance created f.Bar = i * 10 FooList.Add(f) ' Foo object added to listNext

For more information, see:

Option Infer Statement

Scope in Visual Basic

Arrays in Visual Basic

Lists and Collections

.NET collections (of which there are many varieties ­ Lists, Dictionary, etc.) must also instantiated orcreated.

Page 12: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Private myList As List(Of String)..myList.Add("ziggy") ' NullReference

You get the same exception for the same reason ­ myList was only declared, but no instancecreated. The remedy is the same:

myList = New List(Of String)

' Or create instance when declared:Private myList As New List(Of String)

A common oversight is a class which uses a collection Type:

Public Class Foo Private barList As List(Of Bar)

Friend Function BarCount As Integer Return barList.Count End Function

Friend Sub AddItem(newBar As Bar) If barList.Contains(newBar) = False Then barList.Add(newBar) End If End Function

Either procedure will result in a NRE, because barList is only declared, not instantiated. Creating aninstance of Foo will not also create an instance of the internal baList . It may have been the intent todo this in the constructor:

Public Sub New ' Constructor ' Stuff to do when a new Foo is created... barList = New List(Of Bar)End Sub

As before, this is incorrect:

Public Sub New() ' Creates another barList local to this procedure Dim barList As New List(Of Bar)End Sub

For more information, see List(Of T) Class.

Data Provider Objects

Working with databases presents many opportunities for a NullReference because there can be manyobjects (Command, Connection, Transaction, Dataset, DataTable, DataRows....) in use atonce.Note: It does not matter which data provider you are using ­­ MySQL, SQL Server, OleDB, etc.­­ theconcepts are the same.

Example 1

Page 13: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Dim da As OleDbDataAdapterDim ds As DataSetDim MaxRows As Integer

con.Open()Dim sql = "SELECT * FROM tblfoobar_List"da = New OleDbDataAdapter(sql, con)da.Fill(ds, "foobar")con.Close()

MaxRows = ds.Tables("foobar").Rows.Count ' Error

As before, the ds Dataset object was declared, but an instance was never created.The DataAdapter will fill an existing DataSet , not create one. In this case, since ds is a localvariable,the IDE warns you that that this might happen:

When declared as a module/class level variable, as appears to be the case with con , the compilercan't know if the object was created by an upstream procedure. Do not ignore warnings.

Remedy

Dim ds As New DataSet

Example 2

ds = New DataSetda = New OleDBDataAdapter(sql, con)da.Fill(ds, "Employees")

txtID.Text = ds.Tables("Employee").Rows(0).Item(1)txtID.Name = ds.Tables("Employee").Rows(0).Item(2)

A typo is the problem here: Employees vs Employee . There was no DataTable named "Employee"created, so a NullReference results trying to access it. Another potential problem is assuming therewill be Items which may not be so when the SQL includes a WHERE clause.

Remedy

Since this uses one table, using Tables(0) will avoid spelling errors. Examining Rows.Count canalso help:

If ds.Tables(0).Rows.Count > 0 Then txtID.Text = ds.Tables(0).Rows(0).Item(1) txtID.Name = ds.Tables(0).Rows(0).Item(2)End If

Fill is a function returning the number of Rows affected which can also be tested:

If da.Fill(ds, "Employees") > 0 Then...

Example 3

Page 14: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Dim da As New OleDb.OleDbDataAdapter("SELECT TICKET.TICKET_NO, TICKET.CUSTOMER_ID, ... FROM TICKET_RESERVATION AS TICKET INNER JOIN FLIGHT_DETAILS AS FLIGHT ... WHERE [TICKET.TICKET_NO]= ...", con)Dim ds As New DataSetda.Fill(ds)

If ds.Tables("TICKET_RESERVATION").Rows.Count > 0 Then

The DataAdapter will provide TableNames as shown in the previous example, but it does not parsenames from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION") references anon­existent table.

The Remedy is the same, reference the table by index:

If ds.Tables(0).Rows.Count > 0 Then

See also DataTable Class.

Object Paths / Nested

If myFoo.Bar.Items IsNot Nothing Then ...

The code is only testing Items while both myFoo and Bar may also be Nothing. The remedy is totest the entire chain or path of objects one at a time:

If (myFoo IsNot Nothing) AndAlso (myFoo.Bar IsNot Nothing) AndAlso (myFoo.Bar.Items IsNot Nothing) Then ....

AndAlso is important. Subsequent tests will not be performed once the first False condition isencountered. This allows the code to safely 'drill' into the object(s) one 'level' at a time,evaluating myFoo.Bar only after (and if) myFoo is determined to be valid. Object chains or paths canget quite long when coding complex objects:

myBase.myNodes(3).Layer.SubLayer.Foo.Files.Add("somefilename")

It is not possible to reference anything 'downstream' of a null Object. This also applies to controls:

myWebBrowser.Document.GetElementById("formfld1").InnerText = "some value"

Here, myWebBrowser or Document could be Nothing, or the formfld1 element may not exist.

UI Controls

Dim cmd5 As New SqlCommand("select Cartons, Pieces, Foobar " _ & "FROM Invoice where invoice_no = '" & _ Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & _ Me.ListBox1.SelectedItem.ToString.Trim & "' And item_name = '" & _ Me.ComboBox2.SelectedValue.ToString.Trim & "' And expiry_date = '" & _ Me.expiry.Text & "'", con)

Among other things, this code does not anticipate that the user may not have selected something inone or more UI controls. ListBox1.SelectedItem may well be Nothing,so ListBox1.SelectedItem.ToString will result in an NRE.

Page 15: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Remedy

Validate data before using it (also use Option Strict and SQL parameters):

Dim expiry As DateTime ' for text date validationIf (ComboBox5.SelectedItems.Count > 0) AndAlso (ListBox1.SelectedItems.Count > 0) AndAlso (ComboBox2.SelectedItems.Count > 0) AndAlso (DateTime.TryParse(expiry.Text, expiry) Then

'... do stuffElse MessageBox.Show(...error message...)End If

Alternatively, you can use (ComboBox5.SelectedItem IsNot Nothing) AndAlso...

Visual Basic Forms

Public Class Form1

Private NameBoxes = New TextBox(5) Controls("TextBox1"), _ Controls("TextBox2"), Controls("TextBox3"), _ Controls("TextBox4"), Controls("TextBox5"), _ Controls("TextBox6")

' same thing in a different format: Private boxList As New List(Of TextBox) From TextBox1, TextBox2, TextBox3 ...

' Immediate NRE: Private somevar As String = Me.Controls("TextBox1").Text

This is a fairly common way to get an NRE. In C#, depending on how it is coded, the IDE will reportthat Controls does not exist in the current context, or "cannot reference non static member". So, tosome extent this is a VB­only situation. It is also complex, because it can result in failure cascade.

The arrays and collections cannot be initialized this way. This initialization code will run before theconstructor creates the Form or the Controls. As a result:

Lists and Collection will be simply be empty

The Array will contain five elements of Nothing

The somevar assignment will result in an immediate NRE, because Nothing does not havea .Text property

Referencing array elements later will result in a NRE. If you do this in Form_Load , due to an odd bug,the IDE may not report the exception when it happens. The exception will pop up later when your codetries to use the array. This "silent exception" is detailed in this post. For our purposes, the key is thatwhen something catastrophic happens while creating a form (Sub New or Form Load event),exceptions may go unreported, the code exits the procedure and just displays the form.

Since no other code in your Sub New or Form Load event will run after the NRE, a great many otherthings can be left uninitialized.

Page 16: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Sub Form_Load(..._ '... Dim name As String = NameBoxes(2).Text ' NRE ' ... ' More code (which will likely not be executed) ' ...End Sub

Note this applies to any and all control and component references making these illegal where theyare:

Public Class Form1

Private myFiles() As String = Me.OpenFileDialog1.FileName & ... Private dbcon As String = OpenFileDialog1.FileName & ";Jet Oledb..." Private studentName As String = TextBox13.Text

Partial Remedy

It is curious that VB does not provide a warning, but the remedy is to declare the containers at theform level, but initialize them in form load event handler when the controls do exist. This can be donein Sub New as long as your code is after the InitializeComponent call:

' Module level declarationPrivate NameBoxes as TextBox()Private studentName As String

' Form Load, Form Shown or Sub New:'' Using the OP's approach (illegal using OPTION STRICT)NameBoxes = New TextBox() Me.Controls("TextBox1"), Me.Controls("TestBox2"), ...)studentName = TextBox32.Text ' For simple control references

The array code may not be out of the woods yet. Any controls which are in a container control (like aGroupBox or Panel) will not be found in Me.Controls ; they will be in the Controls collection of thatPanel or GroupBox. Nor will a control be returned when the control name is misspelled ("TeStBox2").In such cases, Nothing will again be stored in those array elements and a NRE will result when youattempt to reference it.

These should be easy to find now that you know what you are looking for:

"Button2" resides on a Panel

Remedy

Rather than indirect references by name using the form's Controls collection, use the controlreference:

Page 17: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

' DeclarationPrivate NameBoxes As TextBox()

' Initialization ‐ simple and easy to read, hard to botch:NameBoxes = New TextBox() TextBox1, TextBox2, ...)

' Initialize a ListNamesList = New List(Of TextBox)(TextBox1, TextBox2, TextBox3...)' orNamesList = New List(Of TextBox)NamesList.AddRange(TextBox1, TextBox2, TextBox3...)

Function Returning Nothing

Private bars As New List(Of Bars) ' Declared and created

Public Function BarList() As List(Of Bars) bars.Clear If someCondition Then For n As Integer = 0 to someValue bars.Add(GetBar(n)) Next n Else Exit Function End If

Return barsEnd Function

This is a case where the IDE will warn you that 'not all paths return a value and a NullReferenceException may result'. You can suppress the warning, by replacing Exit Function with Return Nothing , but that does not solve the problem. Anything which tries to use the returnwhen someCondition = False will result in a NRE:

bList = myFoo.BarList()For Each b As Bar in bList ' EXCEPTION ...

Remedy

Replace Exit Function in the function with Return bList . Returning an empty List is not the sameas returning Nothing. If there is a chance that a returned object can be Nothing, test before using it:

bList = myFoo.BarList() If bList IsNot Nothing Then...

Poorly Implemented Try/Catch

A badly implemented Try/Catch can hide where the problem is and result in new ones:

Page 18: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Dim dr As SqlDataReaderTry Dim lnk As LinkButton = TryCast(sender, LinkButton) Dim gr As GridViewRow = DirectCast(lnk.NamingContainer, GridViewRow) Dim eid As String = GridView1.DataKeys(gr.RowIndex).Value.ToString() ViewState("username") = eid sqlQry = "select FirstName, Surname, DepartmentName, ExtensionName, jobTitle, Pager, mailaddress, from employees1 where username='" & eid & "'" If connection.State <> ConnectionState.Open Then connection.Open() End If command = New SqlCommand(sqlQry, connection)

'More code fooing and barring

dr = command.ExecuteReader() If dr.Read() Then lblFirstName.Text = Convert.ToString(dr("FirstName")) ... End If mpe.Show()Catch

Finally command.Dispose() dr.Close() ' <‐‐ NRE connection.Close()End Try

This is a case of an object not being created as expected, but also demonstrates the counterusefulness of an empty Catch.

There is an extra comma in the SQL (after 'mailaddress') which results in an exceptionat .ExecuteReader . After the Catch does nothing, Finally tries to perform clean up, but since youcannot Close a null DataReader object, a brand new NullReferenceException results.

An empty Catch block is the devil's playground. This OP was baffled why he was getting an NRE inthe Finally block. In other situations, an empty Catch may result in something else much furtherdownstream going haywire and cause you to spend time looking at the wrong things in the wrongplace for the problem. (The "silent exception" described above provides the same entertainmentvalue.)

Remedy

Don't use empty Try/Catch blocks ­ let the code crash so you can a) identify the cause b) identify thelocation and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from theperson uniquely qualified to fix them ­ the developer.

DBNull is not the same as Nothing

For Each row As DataGridViewRow In dgvPlanning.Rows If Not IsDBNull(row.Cells(0).Value) Then ...

The IsDBNull function is used to test if a value equals System.DBNull : From MSDN:

The System.DBNull value indicates that the Object represents missing or non­existent data.DBNull is not the same as Nothing, which indicates that a variable has not yet been initialized.

Remedy

Page 19: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

If row.Cells(0) IsNot Nothing Then ...

As before, you can test for Nothing, then for a specific value:

If (row.Cells(0) IsNot Nothing) AndAlso (IsDBNull(row.Cells(0).Value) = False) Then

Example 2

Dim getFoo = (From f In dbContext.FooBars Where f.something = something Select f).FirstOrDefault

If Not IsDBNull(getFoo) Then If IsDBNull(getFoo.user_id) Then txtFirst.Text = getFoo.first_name Else ...

FirstOrDefault returns the first item or the default value, which is Nothing for reference types andnever DBNull:

If getFoo IsNot Nothing Then...

Controls

Dim chk As CheckBox

chk = CType(Me.Controls(chkName), CheckBox)If chk.Checked Then Return chkEnd If

If a CheckBox with chkName can't be found (or exists in a GroupBox), then chk will be Nothing andattempting to reference any property will result in an exception.

Remedy

If (chk IsNot Nothing) AndAlso (chk.Checked) Then ...

The DataGridView

The DGV has a few quirks seen periodically:

dgvBooks.DataSource = loan.BooksdgvBooks.Columns("ISBN").Visible = True ' NullReferenceExceptiondgvBooks.Columns("Title").DefaultCellStyle.Format = "C"dgvBooks.Columns("Author").DefaultCellStyle.Format = "C"dgvBooks.Columns("Price").DefaultCellStyle.Format = "C"

If dgvBooks has AutoGenerateColumns = True , it will create the columns, but it does not name them,so the above code fails when it references them by name.

Remedy

Name the columns manually, or reference by index:

dgvBooks.Columns(0).Visible = True

Page 20: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

Example 2 ­ Beware of the NewRow

xlWorkSheet = xlWorkBook.Sheets("sheet1")

For i = 0 To myDGV.RowCount ‐ 1 For j = 0 To myDGV.ColumnCount ‐ 1 For k As Integer = 1 To myDGV.Columns.Count xlWorkSheet.Cells(1, k) = myDGV.Columns(k ‐ 1).HeaderText xlWorkSheet.Cells(i + 2, j + 1) = myDGV(j, i).Value.ToString() Next NextNext

When your DataGridView has AllowUserToAddRows as True (the default), the Cells in theblank/new row at the bottom will all contain Nothing. Most attempts to use the contents (forexample, ToString ) will result in an NRE.

Remedy

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This workswhether AllowUserToAddRows is true or not:

For Each r As DataGridViewRow in myDGV.Rows If r.IsNewRow = False Then ' ok to use this row

If you do use a For n loop, modify the row count or use Exit For when IsNewRow is true.

My.Settings (StringCollection)

Under certain circumstances, trying to use an item from My.Settings which isa StringCollection can result in a NullReference the first time you use it. The solution is the same,but not as obvious. Consider:

My.Settings.FooBars.Add("ziggy") ' foobars is a string collection

Since VB is managing Settings for you, it is reasonable to expect it to initialize the collection. It will, butonly if you have previously added an initial entry to the collection (in the Settings editor). Since thecollection is (apparently) initialized when an item is added, it remains Nothing when there are noitems in the Settings editor to add.

Remedy

Initialize the settings collection in the form's Load event handler, if/when needed:

If My.Settings.FooBars Is Nothing Then My.Settings.FooBars = New System.Collections.Specialized.StringCollectionEnd If

Typically, the Settings collection will only need to be initialized the first time the application runs. Analternate remedy is to add an initial value to your collection in Project ­> Settings | FooBars, savethe project, then remove the fake value.

Key Points

You probably forgot the New operator.

Page 21: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiPlutonix

community wikiChris B. Behrens

or

Something you assumed would perform flawlessly to return an initialized object to your code, did not.

Don't ignore compiler warnings (ever) and use Option Strict On (always).

MSDN NullReference Exception

share improve this answer edited May 25 at 12:45

4 Excellent post. Happy to see an answer dedicated to VB as I am sure lots of VB only folks get caught up ona lot of the other language answers. – TyCobb Nov 6 '14 at 7:04

1 Great answer, Plutonix. I might suggest moving the tl;dr section to the top though.... :) – Sam Axe Mar17 at 3:39

57

It means that the variable in question is pointed at nothing. I could generate this like so:

SqlConnection connection = null;connection.Open();

That will throw the error because while I've declared the variable " connection ", it's not pointed toanything. When I try to call the member " Open ", there's no reference for it to resolve, and it will throwthe error.

To avoid this error:

1. Always initialize your objects before you try to do anything with them.

2. If you're not sure whether the object is null, check it with object == null .

JetBrains' Resharper tool will identify every place in your code that has the possibility of a nullreference error, allowing you to put in a null check. This error is the number one source of bugs,IMHO.

share improve this answer edited Jun 10 at 10:01

50

It means your code used an object reference variable that was set to null (i.e. it did not reference anactual object instance).

To prevent the error, objects that could be null should be tested for null before being used.

add a comment

add a comment

Page 22: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiJonathan Wood

community wikicode master

community wikiAlex Key

if (myvar != null) // Go ahead and use myvar myvar.property = ...else // Whoops! myvar is null and cannot be used without first // assigning it to an instance reference // Attempting to use myvar here will result in NullReferenceException

share improve this answer edited Jul 28 '14 at 19:17

39

Be aware that regardless of the scenario, the cause is always the same in .NET:

You are trying to use a reference variable whose value is Nothing / null . When the valueis Nothing / null for the reference variable, that means it is not actually holding a reference to aninstance of any object that exists on the heap.

You either never assigned something to the variable, never created an instance of the valueassigned to the variable, or you set the variable equal to Nothing / null manually, or you called afunction that set the variable to Nothing / null for you.

share improve this answer edited Jun 10 at 10:03

27

An example of this exception being thrown is: When you are trying to check something, that is null.

For example:

string testString = null; //Because it doesn't have a value (i.e. it's null; "Length" cannot do what it needs to do)

if (testString.Length == 0) // Throws a nullreferenceexception //Do something

The .NET runtime will throw a NullReferenceException when you attempt to perform an action onsomething which hasn't been instantiated i.e. the code above.

In comparison to an ArgumentNullException which is typically thrown as a defensive measure if amethod expects that what is being passed to it is not null.

More information is in C# NullReferenceException and Null Parameter.

share improve this answer edited Apr 6 at 19:10

add a comment

add a comment

add a comment

Page 23: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiFabian Bigler

19

If you have not initialized a reference type, and you want to set or read one of its properties, it willthrow a NullReferenceException.

Example:

Person p = null;p.Name = "Harry"; <== NullReferenceException occurs here.

You can simply avoid this by checking if the variable is not null:

Person p = null;if (p!=null) p.Name = "Harry"; <== Not going to run to this point

To fully understand why a NullReferenceException is thrown, it is important to know the differencebetween value types and reference types.

So, if you're dealing with value types, NullReferenceExceptions can not occur. Though you need tokeep alert when dealing with reference types!

Only reference types, as the name is suggesting, can hold references or point literally to nothing (or'null'). Whereas value types always contain a value.

Reference types (these ones must be checked):

dynamic

object

string

Value types (you can simply ignore these ones):

Numeric types

Integral types

Floating­point types

decimal

bool

User defined structs

share improve this answer edited Apr 6 at 19:14

3 ­1: since the question is "What is a NullReferenceException", value types are not relevant. – John Saunders May 16 '13 at 22:00

8 @John Saunders: I disagree. As a software developer it is really important to be able to distinguish betweenvalue and reference types. else people will end up checking if integers are null. – Fabian Bigler May 16 '13 at22:28

2 True, just not in the context of this question. – John Saunders May 16 '13 at 22:44

1 Thanks for the hint. I improved it a bit and added an example at the top. I still think mentioning Reference &Value Types is useful. – Fabian Bigler May 16 '13 at 23:02

Page 24: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiJonathon Reinhart

2 I think you haven't added anything that wasn't in the other answers, since the question pre­supposes areference type. – John Saunders May 18 '13 at 23:24

18

Another case where NullReferenceExceptions can happen is the (incorrect) use of the as operator:

class Book public string Name get; set; class Car

Car mycar = new Car();Book mybook = mycar as Book; // Incompatible conversion ‐‐> mybook = null

Console.WriteLine(mybook.Name); // NullReferenceException

Here, Book and Car are incompatible types; a Car cannot be converted/cast to a Book . When thiscast fails, as returns null . Using mybook after this causes a NullReferenceException .

In general, you should use a cast or as , as follows:

If you are expecting the type conversion to always succeed (ie. you know what the object should beahead of time), then you should use a cast:

ComicBook cb = (ComicBook)specificBook;

If you are unsure of the type, but you want to try to use it as a specific type, then use as :

ComicBook cb = specificBook as ComicBook;if (cb != null) // ...

share improve this answer answered Mar 5 '13 at 19:32

This can happen a lot when unboxing a variable. I find it happens often in event handlers after I changed thetype of the UI element but forget to update the code­behind. – Brendan Feb 19 '14 at 0:24

15

You are using the object that contains the null value reference. So it's giving a null exception. In theexample the string value is null and when checking its length, the exception occurred.

Example:

string value = null;if (value.Length == 0) // <‐‐ Causes exception Console.WriteLine(value); // <‐‐ Never reached

The exception error is:

Unhandled Exception:

add a comment

add a comment

Page 25: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiuser1814380

community wikiJeppe Stig Nielsen

System.NullReferenceException: Object reference not set to an instance of an object. atProgram.Main()

share improve this answer edited May 25 at 13:41

How profound! I never considered the 'null' constant a reference value. So this is how C# abstracts a"NullPointer" huh ? B/c as I recall in C++, a NPE can be caused by dereferencing an uninitialized pointer (ie,ref type in c#) whose default value happens to be an address that is not allocated to that process (manycases this would be 0, especially in later versions of C++ that did auto­initialization, which belongs to the OS­ f with it and die beeotch (or just catch the sigkill the OS attacks your process with)). – Samus Arin Jul 31'13 at 18:55

14

Simon Mourier gave this example:

object o = null;DateTime d = (DateTime)o; // NullReferenceException

where an unboxing conversion (cast) from object (or from one of theclasses System.ValueType or System.Enum , or from an interface type) to a value type (otherthan Nullable<> ) in itself gives the NullReferenceException .

In the other direction, a boxing conversion from a Nullable<> which has HasValue equalto false to a reference type, can give a null reference which can then later lead toa NullReferenceException . The classic example is:

DateTime? d = null;var s = d.ToString(); // OK, no exception (no boxing), returns ""var t = d.GetType(); // Bang! d is boxed, NullReferenceException

Sometimes the boxing happens in another way. For example with this non­generic extension method:

public static void MyExtension(this object x) x.ToString();

the following code will be problematic:

DateTime? d = null;d.MyExtension(); // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here.

These cases arise because of the special rules the runtime uses when boxing Nullable<> instances.

share improve this answer edited May 25 at 12:34

10

Adding a case when the class name for entity used in entity framework is same as class name for aweb form code­behind file.

Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an

add a comment

add a comment

Page 26: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiAbhinavRanjan

entity name Contact.

Then following code will throw a NullReferenceException when you call context.SaveChanges()

Contact contact = new Contact Name = "Abhinav";var context = new DataContext();context.Contacts.Add(contact);context.SaveChanges(); // NullReferenceException at this line

For the sake of completeness DataContext class

public class DataContext : DbContext public DbSet<Contact> Contacts get; set;

and Contact entity class. Sometimes entity classes are partial classes so that you can extend them inother files too.

public partial class Contact public string Name get; set;

The error occurs when both the entity and codebehind class are in same namespace. To fix this,rename the entity class or the codebehind class for Contact.aspx.

Reason I am still not sure about the reason. But whenever any of the entity class will extendSystem.Web.UI.Page this error occurs.

For discussion have a look at NullReferenceException in DbContext.saveChanges()

share improve this answer edited Dec 18 '13 at 20:29

10

While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception havebeen addressed in other answers, what many programmers haven't learned yet is how toindependently debug such exceptions during development.

In Visual Studio this is usually easy thanks to the Visual Studio Debugger.

First, make sure that the correct error is going to be caught ­ see How do I allow breaking on'System.NullReferenceException' in VS2010? Note1

Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process. On occasionit may be useful to use Debugger.Break , which will prompt to launch the debugger.

Now, when the NullReferenceException is thrown (or unhandled) the debugger will stop (rememberthe rule set above?) on the line on which the exception occurred. Sometimes the error will be easy tospot.

For instance, in the following line the only code that can cause the exception is if myString evaluatesto null. This can be verified by looking at the Watch Window or running expressions in the ImmediateWindow.

add a comment

Page 27: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiuser2864740

community wiki2 revsJohn Saunders

var x = myString.Trim();

In more advanced cases, such as the following, you'll need to use one of the techniques above(Watch or Immediate Windows) to inspect the expressions to determine if str1 was null orif str2 was null.

var x = str1.Trim() + str2.Trim();

Once where the exception is throw has been located, it's usually trivial to reason backwards to findout where the null value was [incorrectly] introduced ­­

Take the time required to understand the cause of the exception. Inspect for null expressions. Inspectthe previous expressions which could have resulted in such null expressions. Add breakpoints andstep through the program as appropriate. Use the debugger.

1 If Break on Throws is too aggressive and the debugger stops on an NPE in the .NET or 3rd­partylibrary, Break on User­Unhandled can be used to limit the exceptions caught. Additionally, VS2012introduces Just My Code which I recommend enabling as well.

If you are debugging with Just My Code enabled, the behavior is slightly different. With Just MyCode enabled, the debugger ignores first­chance common language runtime (CLR) exceptions thatare thrown outside of My Code and do not pass through My Code

share improve this answer edited May 6 '14 at 21:56

9

Another general case where one might receive this exception involves mocking classes during unittesting. Regardless of the mocking framework being used, you must ensure that all appropriate levelsof the class hierarchy are properly mocked. In particular, all properties of HttpContext which arereferenced by the code under test must be mocked.

See "NullReferenceException thrown when testing custom AuthorizationAttribute" for a somewhatverbose example.

share improve this answer edited Dec 26 '13 at 11:16

7

I have a different perspective to answering this. This sort of answers "what else can I do to avoidit?"

When working across different layers, for example in an MVC application, a controller needsservices to call business operations. In such scenarios Dependency Injection Container can beused to initialize the services to avoid the NullReferenceException. So that means you don't need toworry about checking for null and just call the services from the controller as though they will alwaysto available (and initialized) as either a singleton or a prototype.

add a comment

add a comment

Page 28: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiMukus

community wikiHemant Bavle

Public Class MyController private ServiceA serviceA; private ServiceB serviceB;

public MyController(ServiceA serviceA, ServiceB serviceB) this.serviceA = serviceA; this.serviceB = serviceB;

public void MyMethod() //We don't need to check null because the dependency injection container injects it, provided you took care of bootstrapping it. var someObject = serviceA.DoThis();

share improve this answer edited Oct 25 '14 at 20:23

3 ­1: this only handles a single scenario ­ that of uninitialized dependencies. This is a minority scenario forNullReferenceException. Most cases are simple misunderstanding of how objects work. Next most frequentare other situations where the developer assumed that the object would be initialized automatically. – John Saunders Mar 7 '14 at 0:06

2 All others have already been answered above. – Mukus Mar 7 '14 at 0:23

Dependency injection is not generally used in order to avoid NullReferenceException. I don't believe that youhave found a general scenario here. In any case, if you edit your answer to be more in the styleofstackoverflow.com/a/15232518/76337, then I will remove the downvote. – John Saunders Mar 7 '14 at0:30

6

A NullReferenceException is thrown when we are trying to access Properties of a null object orwhen a string value becomes empty and we are trying to access string methods.

For example:

1. When a string method of an empty string accessed:

string str = string.Empty;str.ToLower(); // throw null reference exception

2. When a property of a null object accessed:

Public Class Person public string Name get; set; Person objPerson;objPerson.Name /// throw Null refernce Exception

share improve this answer edited Jun 10 at 6:04

This is incorrect. String.Empty.ToLower() will not throw a null reference exception. It represents an

add a comment

Page 29: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiNick L.

actual string, albeit an empty one (i.e. "" ). Since this has an object to call ToLower() on, it would notmake sense to throw a null reference exception there. – Kjartan Jul 24 at 6:00

3

On the matter of "what should I do about it", there can be many answers.

A more "formal" way of preventing such error conditions while developing is applying design bycontract in your code. This means you need to set class invariants, and/or evenfunction/methodpreconditions and postconditions on your system, while developing.

In short, class invariants ensure that there will be some constraints in your class that will not getviolated in normal use (and therefore, the class will not get in an inconsistentstate). Preconditionsmean that data given as input to a function/method must follow some constraintsset and never violate them, and postconditions mean that a function/method output must follow the setconstraints again without ever violating them. Contract conditions should never be violated duringexecution of a bug­free program, therefore design by contract is checked in practice in debug mode,while being disabled in releases, to maximize the developed system performance.

This way, you can avoid NullReferenceException cases that are results of violation of theconstraints set. For example, if you use an object property X in a class and later try to invoke one ofits methods and X has a null value, then this will lead to NullReferenceException :

public X get; set;

public void InvokeX() X.DoSomething(); // if X value is null, you will get a NullReferenceException

But if you set "property X must never have a null value" as method precondition, then you can preventthe scenario described before:

//Using code contracts:[ContractInvariantMethod]protected void ObjectInvariant () Contract.Invariant ( X != null ); //...

For this cause, Code Contracts project exists for .NET applications (take a look here).

Alternatively, design by contract can be applied using assertions (look here for more).

share improve this answer edited Dec 26 '14 at 0:15

1 I thought to add this as no one mentioned this, and as far as it exists as an approach, my intention was toenrich the topic. – Nick L. Dec 26 '14 at 1:03

1 Thank you for enriching the topic. I have given my opinion of your addition. Now others can do the same. – John Saunders Dec 26 '14 at 1:05

1 I thought this was a worthwhile addition to the topic given that this is a highly viewed thread. I've heard ofcode contracts before and this was a good reminder to consider using them. – VoteCoffee Jan 8 at 2:03

add a comment

add a comment

Page 30: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

community wikiTravis Heeter

0

TL;DR: Try using Html.Partial instead of Renderpage

I know this is such a specific and stupid, possibly obvious thing, but it took me a while to figure out, soI thought I'd put my solution here because I couldn't find it in any other posts.

I was getting Object reference not set to an instance of an object when I tried to render a Viewwithin a View by sending it a Model, like this:

@ MyEntity M = new MyEntity();@RenderPage("_MyOtherView.cshtml", M); // error in _MyOtherView, the Model was Null

Debugging showed the model was Null inside MyOtherView. Until I changed it to:

@ MyEntity M = new MyEntity();@Html.Partial("_MyOtherView.cshtml", M);

And it worked.

Furthermore, the reason I didn't have Html.Partial to begin with was becauseVS sometimesthrows error­looking squiggly lines under Html.Partial if it's inside a differentlyconstructed foreach loop, even though it's not really an error:

@inherits System.Web.Mvc.WebViewPage@ ViewBag.Title = "Entity Index"; List<MyEntity> MyEntities = new List<MyEntity>(); MyEntities.Add(new MyEntity()); MyEntities.Add(new MyEntity()); MyEntities.Add(new MyEntity());<div> @ foreach(var M in MyEntities) //squiggly lines below. Hovering says: cannot convert method group 'partial' to non‐delegate type Object, did you intend to envoke the Method? @Html.Partial("MyOtherView.cshtml"); </div>

But I was able to run the application with no problems with this "error". I was able to get rid of the errorby changing the structure of the foreach loop to look like this:

@foreach(var M in MyEntities) ...

Although I have a feeling it was because VS was misreading the Ampersands and Brackets.

share improve this answer edited Jul 27 at 11:47

Page 31: c# - What is a NullReferenceException and How Do I Fix It_ - Stack Overflow

You wanted Html.Partial , not @Html.Partial – John Saunders Jul 24 at 13:55

Also, please show which line threw the exception, and why. – John Saunders Jul 24 at 13:56

The error occurred in MyOtherView.cshtml, which I did not include here, because the Model was not beingproperly sent in (it was Null ), so I knew the error was with how I was sending the Model in. – Travis HeeterJul 27 at 11:44

protected by ken2k Dec 4 '13 at 10:11Thank you for your interest in this question. Because it has attracted low­quality answers, posting an answer nowrequires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

add a comment