c# - unity - system.nullreferenceexception object reference not set to an instance of an object




什麼是NullReferenceException,以及如何解決它? (20)

我有一些代碼,當它執行時,它會拋出一個NullReferenceException ,並說:

你調用的對像是空的。

這是什麼意思,我能做些什麼來解決這個錯誤?


NullReference異常 - Visual Basic

Visual BasicNullReference ExceptionC#中NullReference Exception沒有區別。 畢竟,他們都報告他們都使用.NET Framework中定義的相同異常。 Visual Basic特有的原因很少見(可能只有一種)。

這個答案將使用Visual Basic術語,語法和上下文。 所使用的示例來自大量過去的問題。 這是通過使用帖子中常見的情況來最大化相關性。 還為可能需要它的人提供了更多解釋。 類似於你的例子可能在這裡列出。

注意:

  1. 這是基於概念的:沒有代碼可以粘貼到您的項目中。 它旨在幫助您了解導致NullReferenceException (NRE)的原因,如何找到它,如何解決該問題以及如何避免它。 NRE可能會有很多種方式,所以這不太可能是你唯一的遭遇。
  2. 這些例子(來自的帖子)並不總是展示最好的方式來做一些事情。
  3. 通常,使用最簡單的補救措施。

基本含義

“對象未設置為對象實例”消息表示您正在嘗試使用尚未初始化的對象。 這歸結為其中之一:

  • 你的代碼聲明了一個對像變量,但它沒有初始化它(創建一個實例或' 實例化 '它)
  • 你的代碼假設會初始化一個對象,但沒有
  • 可能地,其他代碼過早地使仍在使用的對象無效

尋找原因

由於問題是一個Nothing的對象引用,答案是要檢查它們以找出哪一個。 然後確定它未被初始化的原因。 將鼠標放在各種變量上,Visual Studio(VS)將顯示它們的值 - 罪魁禍首將是Nothing

您還應該從相關代碼中刪除任何Try / Catch塊,尤其是那些Catch塊中沒有任何內容的代碼塊。 這會導致您的代碼在嘗試使用Nothing的對象時崩潰。 這是你想要的,因為它可以確定問題的確切位置 ,並允許你識別造成它的對象。

Catch中的MsgBox顯示Error while...將沒有多大幫助。 這種方法也會導致問題非常糟糕 ,因為您無法描述實際的異常,所涉及的對像或者代碼行。

你也可以使用Locals WindowDebug - > Windows - > Locals )來檢查你的對象。

一旦你知道問題出在什麼地方,通常很容易解決問題,並且比發布新問題更快。

也可以看看:

示例和補救措施

類對象/創建實例

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

問題是Dim不會創建一個CashRegister 對象 ; 它只聲明一個名為該類型的reg的變量。 聲明一個對像變量並創建一個實例是兩件不同的事情。

補救

New運算符通常可用於在聲明它時創建實例:

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

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

以後只適合於創建實例:

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

注意: 不要在過程中再次使用Dim ,包括構造函數( Sub New ):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

這將創建一個局部變量reg ,它只存在於該上下文(sub)中。 您將在其他地方使用的模塊級別為Scopereg變量保持為Nothing

缺少New運算符是NullReference Exceptions的第一個原因,在所檢查的問題中看到。

Visual Basic嘗試使用New重複清除該過程:使用New Operator創建一個對象並調用Sub New - 構造函數 - 您的對象可以在其中執行任何其他初始化。

要明確, Dim (或Private )只聲明一個變量及其Type 。 變量的範圍 - 無論它存在於整個模塊/類還是程序的本地 - 由其聲明的位置決定。 Private | Friend | Public Private | Friend | Public定義訪問級別,而不是范圍

有關更多信息,請參閱:

數組

數組也必須實例化:

Private arr as String()

這個數組只是被聲明的,沒有被創建。 有幾種方法可以初始化數組:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

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

注意:從VS 2010開始,當使用文字和Option Infer初始化本地數組時, As <Type>New元素是可選的:

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

數據類型和數組大小是從正在分配的數據中推斷出來的。 類/模塊級聲明仍然需要As <Type> with Option Strict

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

示例:類對像數組

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

該數組已創建,但其中的Foo對象尚未創建。

補救

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

使用List(Of T)將會使得沒有有效對象的元素變得非常困難:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim 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 list
Next

有關更多信息,請參閱:

列表和集合

.NET集合(其中有許多種類 - 列表,詞典等)也必須實例化或創建。

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

由於相同的原因,您會得到相同的異常 - myList僅被聲明,但沒有創建實例。 補救措施是一樣的:

myList = New List(Of String)

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

常見的疏忽是使用集合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

任一過程都會導致NRE,因為barList只是聲明的,沒有實例化。 創建Foo的實例也不會創建內部barList的實例。 它可能是在構造函數中執行此操作的意圖:

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

和以前一樣,這是不正確的:

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

有關更多信息,請參見List(Of T)

數據提供者對象

使用數據庫為NullReference提供了很多機會,因為可以同時使用許多對象( CommandConnectionTransactionDatasetDataTableDataRows ....)。 注意:您使用的是哪種數據提供程序無關緊要 - MySQL,SQL Server,OleDB等 - 概念相同。

例1

Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim 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

與之前一樣, ds數據集對像已聲明,但實例從未創建。 DataAdapter將填充現有的DataSet ,而不是創建一個。 在這種情況下,由於ds是局部變量, 因此IDE會警告您可能會發生這種情況:

當被聲明為模塊/類級別變量時,與con似乎一樣,編譯器無法知道對像是否由上游過程創建。 不要忽視警告。

補救

Dim ds As New DataSet

例2

ds = New DataSet
da = 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)

錯字是這裡的一個問題: Employees vs Employee 。 沒有創建名為“Employee”的DataTable ,因此嘗試訪問它的NullReferenceException結果。 另一個潛在的問題是假定當SQL包含WHERE子句時,會出現不可能出現的Items

補救

由於這使用一個表,所以使用Tables(0)將避免拼寫錯誤。 檢查Rows.Count還可以幫助:

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是一個函數,返回受影響的Rows數,也可以進行測試:

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

例3

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 DataSet
da.Fill(ds)

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

DataAdapter將提供如上例所示的TableNames ,但它不會從SQL或數據庫表中解析名稱。 因此, ds.Tables("TICKET_RESERVATION")引用一個不存在的表。

補救措施是一樣的,請參考表格索引:

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

另請參閱DataTable類

對象路徑/嵌套

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

代碼只是測試ItemsmyFooBar可能是Nothing。 補救措施是一次測試一個對象的整個鍊或路徑:

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

AndAlso也很重要。 一旦遇到第一個False條件,後續測試將不會執行。 這允許代碼一次安全地“鑽取”到一個“級別”的對像中,只有在(和if) myFoo被確定為有效之後才評估myFoo.Bar 。 編碼複雜對象時,對象鍊或路徑可能會變得很長:

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

無法引用null對象的任何'下游'。 這也適用於控制:

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

在這裡, myWebBrowserDocument可能是Nothing,或者formfld1元素可能不存在。

UI控件

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)

除此之外,此代碼不會預期用戶可能沒有在一個或多個UI控件中選擇某些內容。 ListBox1.SelectedItem可能是Nothing ,因此ListBox1.SelectedItem.ToString將導致NRE。

補救

在使用它之前驗證數據(也使用Option Strict和SQL參數):

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

    '... do stuff
Else
    MessageBox.Show(...error message...)
End If

或者,您可以使用(ComboBox5.SelectedItem IsNot Nothing) AndAlso...

Visual Basic窗體

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

這是獲得NRE的一種相當常見的方式。 在C#中,根據編碼的方式,IDE將報告Controls在當前上下文中不存在,或者“不能引用非靜態成員”。 所以,在某種程度上,這是一個純VB的情況。 它也很複雜,因為它可能導致級聯失敗。

數組和集合不能通過這種方式進行初始化。 此初始化代碼將構造函數創建FormControls 之前運行。 結果是:

  • 列表和集合將簡單地為空
  • 該數組將包含Nothing的五個元素
  • somevar賦值將導致立即NRE,因為Nothing沒有.Text屬性

稍後引用數組元素將導致NRE。 如果您在Form_Load執行此操作,由於存在奇怪的錯誤,IDE在發生異常時可能不會報告異常。 當您的代碼嘗試使用該數組時,將在以後彈出該異常。 這篇“無聲的例外” 在這篇文章中有詳細介紹 。 就我們的目的而言,關鍵在於,當創建表單( Sub NewForm Load事件)時發生災難性事件時,異常可能未被報告,代碼退出過程並僅顯示表單。

由於Sub NewForm Load事件中沒有其他代碼會在NRE之後運行,因此很多其他事情可能會保持未初始化狀態。

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

請注意,這適用於任何以及所有控制和組件引用,因為它們是非法的:

Public Class Form1

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

部分補救措施

很奇怪VB沒有提供警告,但補救措施是在表單級別聲明容器,但在控件確實存在時,在表單加載事件處理程序中初始化它們。 只要您的代碼在InitializeComponent調用之後,就可以在Sub New完成:

' Module level declaration
Private 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

數組代碼可能還沒有走出困境。 Me.Controls找不到任何位於容器控件(如GroupBoxPanel )中的Me.Controls ; 他們將在該Panel或GroupBox的Controls集合中。 當控件名稱拼寫錯誤時( "TeStBox2" ),也不會返回控件。 在這種情況下, Nothing將再次存儲在這些數組元素中,並且當您嘗試引用它時會導致NRE。

這些應該很容易找到,現在你知道你在找什麼:

“Button2”駐留在Panel

補救

而不是按名稱使用表單的Controls集合進行間接引用,請使用控件引用:

' Declaration
Private NameBoxes As TextBox()

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

' Initialize a List
NamesList = New List(Of TextBox)({TextBox1, TextBox2, TextBox3...})
' or
NamesList = New List(Of TextBox)
NamesList.AddRange({TextBox1, TextBox2, TextBox3...})

函數返回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 bars
End Function

這種情況下,IDE會警告您' 並非所有路徑都返回值並且可能導致NullReferenceException '。 您可以通過將Exit Function替換為Return Nothing來取消警告,但這並不能解決問題。 當someCondition = False時,任何試圖使用return的都會導致NRE:

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

補救

使用Return bList替換Exit Function中的Exit Function 。 返回 List與返回Nothing 。 如果返回的對像有可能是Nothing ,請在使用之前進行測試:

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

很難實施Try / Catch

嚴重實施的Try / Catch可以隱藏問題所在並導致新問題:

Dim dr As SqlDataReader
Try
    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

這是一個沒有按預期創建的對象,但也演示了一個空Catch的計數器實用性。

There is an extra comma in the SQL (after 'mailaddress') which results in an exception at .ExecuteReader . After the Catch does nothing, Finally tries to perform clean up, but since you cannot 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 in the Finally block. In other situations, an empty Catch may result in something else much further downstream going haywire and cause you to spend time looking at the wrong things in the wrong place for the problem. (The "silent exception" described above provides the same entertainment value.)

補救

Don't use empty Try/Catch blocks - let the code crash so you can a) identify the cause b) identify the location and c) apply a proper remedy. Try/Catch blocks are not intended to hide exceptions from the person 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.

補救

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

例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 and never DBNull :

If getFoo IsNot Nothing Then...

控制

Dim chk As CheckBox

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

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

補救

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

The DataGridView

The DGV has a few quirks seen periodically:

dgvBooks.DataSource = loan.Books
dgvBooks.Columns("ISBN").Visible = True       ' NullReferenceException
dgvBooks.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.

補救

Name the columns manually, or reference by index:

dgvBooks.Columns(0).Visible = True

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
    Next
Next

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

補救

Use a For/Each loop and test the IsNewRow property to determine if it is that last row. This works whether 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 is a StringCollection can result in a NullReference the first time you use it. The solution is the same, but not as obvious. 考慮:

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, but only if you have previously added an initial entry to the collection (in the Settings editor). Since the collection is (apparently) initialized when an item is added, it remains Nothing when there are no items in the Settings editor to add.

補救

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.StringCollection
End If

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

Key Points

You probably forgot the New operator.

要么

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


原因是什麼?

底線

您試圖使用null (或VB.NET中的Nothing )。 這意味著你要么將它設置為null ,要么你根本沒有設置它。

像其他任何東西一樣, null傳遞。 如果方法“A”中為null ,則可能是該方法“B”將null傳遞方法“A”。

本文的其餘部分會更詳細地介紹許多程序員經常犯的錯誤,這可能會導致NullReferenceException

進一步來說

NullReferenceException的運行時總是意味著同樣的事情:您正在嘗試使用引用,並且引用未初始化(或者它曾經初始化,但不再初始化)。

這意味著引用為null ,並且您無法通過null引用訪問成員(例如方法)。 最簡單的情況:

string foo = null;
foo.ToUpper();

這將在第二行中拋出NullReferenceException ,因為您無法在指向nullstring引用上調用實例方法ToUpper()

調試

你如何找到NullReferenceException的來源? 除了查看異常本身,這些異常本身將會發生在它發生的位置,Visual Studio中調試的一般規則適用於:放置戰略斷點並檢查變量 ,方法是將鼠標懸停在其名稱上,打開(快速)觀察窗口或使用各種調試面板,如本地和汽車。

如果您想查找引用的位置或未設置,請右鍵單擊其名稱並選擇“查找所有引用”。 然後,您可以在每個找到的位置放置一個斷點,並使用附加的調試器運行程序。 每當調試器斷開這樣一個斷點時,您需要確定您是否期望引用是非空的,檢查該變量,並在您希望的時候驗證它是否指向一個實例。

通過這種方式遵循程序流程,您可以找到實例不應該為null的位置,以及為什麼它沒有正確設置。

例子

可引發異常的一些常見情況:

通用

ref1.ref2.ref3.member

如果ref1或ref2或ref3為null,那麼您將得到一個NullReferenceException 。 如果你想解決這個問題,那麼通過將表達式重寫為更簡單的等價形式來找出哪一個是空的:

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

特別是,在HttpContext.Current.User.Identity.NameHttpContext.Current可能為null,或者User屬性可能為null,或者Identity屬性可能為null。

間接

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.
    }
}

如果你想避免child(Person)空引用,你可以在父(Book)對象的構造函數中初始化它。

嵌套對像初始化器

這同樣適用於嵌套對像初始值設定項:

Book b1 = new Book { Author = { Age = 45 } };

這意味著

Book b1 = new Book();
b1.Author.Age = 45;

雖然使用了new關鍵字,但它僅創建Book的新實例,但不創建Person的新實例,所以Author的屬性仍然為null

嵌套集合初始化器

public class Person {
    public ICollection<Book> Books { get; set; }
}
public class Book {
    public string Title { get; set; }
}

嵌套集合初始化器的行為相同:

Person p1 = new Person {
    Books = {
        new Book { Title = "Title1" },
        new Book { Title = "Title2" },
    }
};

這意味著

Person p1 = new Person();
p1.Books.Add(new Book { Title = "Title1" });
p1.Books.Add(new Book { Title = "Title2" });

new Person只創建new Person的實例,但Books集合仍然為null 。 集合初始化器語法不會為p1.Books創建集合,它只能轉換為p1.Books.Add(...)語句。

排列

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

數組元素

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.

鐵血陣列

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.

集合/列表/字典

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

範圍變量(間接/延遲)

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.

活動

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
    }
}

錯誤的命名約定:

如果您將字段命名為與當地人不同,則可能意識到您從未初始化該字段。

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);
    }
}

這可以通過遵循約定為字段添加下劃線來解決:

private Customer _customer;

ASP.NET頁面生命週期:

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會話值

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

ASP.NET MVC空視圖模型

如果在ASP.NET MVC視圖中引用@Model的屬性時發生異常,則需要了解在return視圖時, Model會在操作方法中設置。 當您從控制器返回一個空模型(或模型屬性)時,當視圖訪問它時會發生異常:

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

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

<p>@Model.somePropertyName</p> <!-- Also throws -->

WPF控件創建順序和事件

WPF控件是在調用InitializeComponent中按照它們出現在可視化樹中的順序創建的。 在InitializeComponent引用後期創建的控件的過程中觸發事件處理程序等的早期創建控件時,將引發NullReferenceException

例如 :

<Grid>
    <!-- Combobox declared first -->
    <ComboBox Name="comboBox1" 
              Margin="10"
              SelectedIndex="0" 
              SelectionChanged="comboBox1_SelectionChanged">
        <ComboBoxItem Content="Item 1" />
        <ComboBoxItem Content="Item 2" />
        <ComboBoxItem Content="Item 3" />
    </ComboBox>

    <!-- Label declared later -->
    <Label Name="label1" 
           Content="Label"
           Margin="10" />
</Grid>

這裡comboBox1是在label1之前創建的。 如果comboBox1_SelectionChanged試圖引用`label1,它還不會被創建。

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

更改XAML中聲明的順序(即,在comboBox1之前列出label1 ,忽略設計原理問題,至少可以解決NullReferenceException

as投射

var myThing = someObject as Thing;

這不會拋出InvalidCastException,但在轉換失敗時(以及someObject本身為null)時返回null。 所以要注意這一點。

LINQ FirstOrDefault()和SingleOrDefault()

沒有任何內容時,Plain First()Single()異常。 在這種情況下,“OrDefault”版本返回null。 所以要注意這一點。

的foreach

當您嘗試迭代空集合時, foreach會拋出。 通常由返回集合的方法導致意外的null結果。

 List<int> list = null;    
 foreach(var v in list) { } // exception

更現實的例子 - 從XML文檔中選擇節點。 如果找不到節點,將會拋出,但初始調試顯示所有屬性都有效:

 foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))

避免的方法

顯式檢查null並忽略空值。

如果您希望引用有時為空,則可以在訪問實例成員之前檢查它是否為null

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

顯式檢查null並提供默認值。

方法調用您期望返回的實例可以返回null ,例如找不到找到的對象時。 在這種情況下,您可以選擇返回默認值:

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

明確檢查方法調用中的null並拋出一個自定義異常。

你也可以拋出一個自定義的異常,只在調用代碼中捕獲它:

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;
}

如果值不應為null ,則使用Debug.Assert以在發生異常之前捕獲問題。

當你在開發過程中知道某個方法可能會,但從不應該返回null ,可以使用Debug.Assert()在發生時盡快中斷:

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.
}

雖然這個檢查不會在你的發布版本中結束 ,但是當它在發布模式下運行時, book == null時,會再次拋出NullReferenceException

對於可為null的值類型,使用GetValueOrDefault()可以在它們為null時提供默認值。

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

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

使用空合併運算符: ?? [C#]或If() [VB]。

遇到null時提供默認值的簡寫:

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;
}

使用null條件運算符: ?.?[x]用於數組(可用於C#6和VB.NET 14):

這有時也被稱為安全導航或埃爾維斯(在它的形狀之後)運營商。 如果運算符左側的表達式為空,則不會評估右側,而是返回null。 這意味著這樣的情況:

var title = person.Title.ToUpper();

如果這個人沒有標題,這會拋出一個異常,因為它試圖在一個空值屬性上調用ToUpper

在C#5及以下版本中,可以通過以下方式來保護它:

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

現在title變量將是null,而不是引發異常。 C#6為此引入了更短的語法:

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

這將導致title變量為null ,並且如果person.Titlenull則不會調用ToUpper

當然,您仍然需要檢查null的title ,或者將空條件運算符與空合併運算符( ?? )一起使用以提供默認值:

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

// combining the `?` and the `??` operator
int titleLength = title?.Length ?? 0;

同樣,對於數組,您可以使用?[i] ,如下所示:

int[] myIntArray=null;
var i=5;
int? elem = myIntArray?[i];
if (!elem.HasValue) Console.WriteLine("No value");

這將執行以下操作:如果myIntArray為null,則表達式返回null,您可以安全地檢查它。 如果它包含一個數組,它將執行相同的操作: elem = myIntArray[i]; 並返回第i 元素。


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

I was getting Object reference not set to an instance of an object when I tried to render a View within 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 because Visual Studio sometimes throws error-looking squiggly lines under Html.Partial if it's inside a differently constructed 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 error by changing the structure of the foreach loop to look like this:

@foreach(var M in MyEntities){
    ...
}

Although I have a feeling it was because Visual Studio was misreading the ampersands and brackets.


What can you do about it?

There is a lot of good answers here explaining what a null reference is and how to debug it. But there is very little on how to prevent the issue or at least make it easier to catch.

Check arguments

For example, methods can check the different arguments to see if they are null and throw an ArgumentNullException , an exception obviously created for this exact purpose.

The constructor for the ArgumentNullException even takes the name of the parameter and a message as arguments so you can tell the developer exactly what the problem is.

public void DoSomething(MyObject obj) {
    if(obj == null) 
    {
        throw new ArgumentNullException("obj", "Need a reference to obj.");
    }
}

Use Tools

There are also several libraries that can help. "Resharper" for example can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute

There's "Microsoft Code Contracts" where you use syntax like Contract.Requires(obj != null) which gives you runtime and compile checking: Introducing Code Contracts .

There's also "PostSharp" which will allow you to just use attributes like this:

public void DoSometing([NotNull] obj)

By doing that and making PostSharp part of your build process obj will be checked for null at runtime. See: PostSharp null check

Plain Code Solution

Or you can always code your own approach using plain old code. For example here is a struct that you can use to catch null references. It's modeled after the same concept as Nullable<T> :

[System.Diagnostics.DebuggerNonUserCode]
public struct NotNull<T> where T: class
{
    private T _value;

    public T Value
    {
        get
        {
            if (_value == null)
            {
                throw new Exception("null value not allowed");
            }

            return _value;
        }
        set
        {
            if (value == null)
            {
                throw new Exception("null value not allowed.");
            }

            _value = value;
        }
    }

    public static implicit operator T(NotNull<T> notNullValue)
    {
        return notNullValue.Value;
    }

    public static implicit operator NotNull<T>(T value)
    {
        return new NotNull<T> { Value = value };
    }
}

You would use very similar to the same way you would use Nullable<T> , except with the goal of accomplishing exactly the opposite - to not allow null . 這裡有些例子:

NotNull<Person> person = null; // throws exception
NotNull<Person> person = new Person(); // OK
NotNull<Person> person = GetPerson(); // throws exception if GetPerson() returns null

NotNull<T> is implicitly cast to and from T so you can use it just about anywhere you need it. For example, you can pass a Person object to a method that takes a NotNull<Person> :

Person person = new Person { Name = "John" };
WriteName(person);

public static void WriteName(NotNull<Person> person)
{
    Console.WriteLine(person.Value.Name);
}

As you can see above as with nullable you would access the underlying value through the Value property. Alternatively, you can use an explicit or implicit cast, you can see an example with the return value below:

Person person = GetPerson();

public static NotNull<Person> GetPerson()
{
    return new Person { Name = "John" };
}

Or you can even use it when the method just returns T (in this case Person ) by doing a cast. For example, the following code would just like the code above:

Person person = (NotNull<Person>)GetPerson();

public static Person GetPerson()
{
    return new Person { Name = "John" };
}

Combine with Extension

Combine NotNull<T> with an extension method and you can cover even more situations. Here is an example of what the extension method can look like:

[System.Diagnostics.DebuggerNonUserCode]
public static class NotNullExtension
{
    public static T NotNull<T>(this T @this) where T: class
    {
        if (@this == null)
        {
            throw new Exception("null value not allowed");
        }

        return @this;
    }
}

And here is an example of how it could be used:

var person = GetPerson().NotNull();

GitHub上

For your reference I made the code above available on GitHub, you can find it at:

https://github.com/luisperezphd/NotNull

Related Language Feature

C# 6.0 introduced the "null-conditional operator" that helps with this a little. With this feature, you can reference nested objects and if any one of them is null the whole expression returns null .

This reduces the number of null checks you have to do in some cases. The syntax is to put a question mark before each dot. Take the following code for example:

var address = country?.State?.County?.City;

Imagine that country is an object of type Country that has a property called State and so on. If country , State , County , or City is null then address will be null . Therefore you only have to check whether address is null`.

It's a great feature, but it gives you less information. It doesn't make it obvious which of the 4 is null.

Built-in like Nullable?

C# has a nice shorthand for Nullable<T> , you can make something nullable by putting a question mark after the type like so int?

It would be nice if C# had something like the NotNull<T> struct above and had a similar shorthand, maybe the exclamation point (!) so that you could write something like: public void WriteName(Person! person) .


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

Suppose you have a web form Contact.aspx whose codebehind class is Contact and you have an 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 in other 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 extend System.Web.UI.Page this error occurs.

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


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

例如:

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 on something which hasn't been instantiated ie the code above.

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

More information is in C# NullReferenceException and Null Parameter .


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

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


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, but this can happen in more "late-binding" intricate scenarios where the null object has been returned from some 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 a piece of code that will be equivalent to the cast code above. And this will raise a NullReferenceException that is quite difficult to spot, because it lies in ASP.NET generated code which compiles fine...


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

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

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();
    }
}

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.


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

例:

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 difference between value types and reference types .

So, if you're dealing with value types , NullReferenceExceptions can not occur. Though you need to keep 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):

  • 動態
  • 目的

Value types (you can simply ignore these ones):

  • Numeric types
  • Integral types
  • Floating-point types
  • 十進制
  • 布爾
  • User defined structs

Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:

Edge case #1: concurrent access to a Dictionary

Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference or even (more frequent) a KeyNotFoundException when you try to access a key from two concurrent threads. The exception is quite misleading in this case.

Edge case #2: unsafe code

If a NullReferenceException is thrown by unsafe code, you might look at your pointer variables, and check them for IntPtr.Zero or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.

(Another reason for non-using unsafe code unless you need it, by the way)


It means you are trying to manipulate something which has reference but not yet initialized
The first thing to do here is check every instance created.

Use breakpoints , watches , inspect your varibale values.
Follow stack trace and search for exact row and column which is creating problem


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

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

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
}

NullReferenceException or Object reference not set to an instance of an object occurs when an object of the class you are trying to use is not instantiated. 例如:

Assume that you have a class named Student.

public class Student
{
    private string FirstName;
    private string LastName;
    public string GetFullName()
    {
        return FirstName + LastName;
    }
}

Now, consider another class where you are trying to retrieve the student's full name.

public class StudentInfo
{      
    public string GetStudentName()
    {
        Student s;
        string fullname = s.GetFullName();
        return fullname;
    }        
}

As seen in the above code, the statement Student s - only declares the variable of type Student, note that the Student class is not instantiated at this point. Hence, when the statement s.GetFullName() gets executed, it will throw the NullReferenceException.


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 by contract in your code. This means you need to set class invariants , and/or even function/method preconditions and postconditions on your system, while developing.

In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution 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 the constraints set. For example, if you use an object property X in a class and later try to invoke one of its 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 prevent the scenario described before:

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

For this cause, Code Contracts project exists for .NET applications.

Alternatively, design by contract can be applied using assertions .

UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language .


The error line "Object reference not set to an instance of an object. " states that you have not assigned instance object to a object reference and still you are accessing properies/methods of that object.

for example: let say you have a class called myClass and it contains one property prop1.

public Class myClass
{
   public int prop1 {get;set;}
}

Now you are accessing this prop1 in some other class just like below:

public class Demo
{
     public void testMethod()
     {
        myClass ref = null;
        ref.prop1 = 1;  //This line throws error
     }
}

above line throws error because reference of class myClass is declared but not instantiated or an instance of object is not assigned to referecne of that class.

To fix this you have to instantiate (assign object to reference of that class).

public class Demo
{
     public void testMethod()
     {
        myClass ref = null;
        ref = new myClass();
        ref.prop1 = 1;  
     }
}

To use methods and member of an object you first have to create that object. If you didn't create it (variable that should hold the object is not initialized), but you try to use it's methods or variables you'll get that error.

Sometime you may just forgot to do initialization.

Edited: new can't return null, but fire's exception when failed. Long time ago it was the case in some languages, but not any more. Thanks @John Saunders for pointing that out.


While what causes a NullReferenceExceptions and approaches to avoid/fix such an exception have been addressed in other answers, what many programmers haven't learned yet is how to independently 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? Note 1

Then either Start with Debugging (F5) or Attach [the VS Debugger] to Running Process . On occasion it 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 (remember the rule set above?) on the line on which the exception occurred. Sometimes the error will be easy to spot.

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

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 or if 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 find out where the null value was [incorrectly] introduced --

Take the time required to understand the cause of the exception. Inspect for null expressions. Inspect the previous expressions which could have resulted in such null expressions. Add breakpoints and step 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-party library, Break on User-Unhandled can be used to limit the exceptions caught. Additionally, VS2012 introduces 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 My Code enabled, the debugger ignores first-chance common language runtime (CLR) exceptions that are thrown outside of My Code and do not pass through My Code


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

例:

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

The exception error is:

Unhandled Exception:

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





nullreferenceexception