c# – What is a NullReferenceException, and how do I fix it?


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

This answer will use Visual Basic terms, syntax, and context. The examples used come from a large number of past Stack  Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example 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 help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how 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 in the first place.
  3. Typically, the simplest remedy is used.

Basic Meaning

The message “Object not set to an instance of Object” means you are trying to use an object which has not 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 out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values – the culprit will be Nothing.

IDE debug display

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

A MsgBox in the Catch which displays Error while... will be of little help. This method also leads to very bad Stack  Overflow questions, because you can’t describe the actual exception, the object involved 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 a new question.

See also:

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 variable named reg of that Type. Declaring an object variable and creating an instance are two different things.

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 CashRegister
End Sub

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

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

Visual Basic tries to make the process clear repeatedly using New: Using the New Operator creates a new object and calls Sub New — the constructor — where your object can perform any other 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 is declared. Private | Friend | Public defines the access level, not Scope.

For more information, see:


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:

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

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.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations 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       ' Exception
Next

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

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

For more information, see:


Lists and Collections

.NET collections (of which there are many varieties – Lists, Dictionary, etc.) must also be instantiated or created.

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 instance created. The remedy is the same:

myList = New List(Of String)

' Or create an 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 an NRE, because barList is only declared, not instantiated. Creating an instance of Foo will not also create an instance of the internal barList. It may have been the intent to do 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 many objects (Command, Connection, Transaction, Dataset, DataTable, DataRows….) in use at once. Note: It does not matter which data provider you are using — MySQL, SQL Server, OleDB, etc. — the concepts are the same.

Example 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

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 local variable, the IDE warns you that this might happen:

img

When declared as a module/class level variable, as appears to be the case with con, the compiler can’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 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)

A typo is a problem here: Employees vs Employee. There was no DataTable named “Employee” created, so a NullReferenceException results trying to access it. Another potential problem is assuming there will 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 can also 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

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

The DataAdapter will provide TableNames as shown in the previous example, but it does not parse names from the SQL or database table. As a result, ds.Tables("TICKET_RESERVATION") references a non-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 to test 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 is encountered. 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 can get 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 in one or more UI controls. ListBox1.SelectedItem may well be Nothing, so ListBox1.SelectedItem.ToString will result in an NRE.

Remedy

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

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

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 report that Controls does not exist in the current context, or “cannot reference non-static member”. So, to some extent, this is a VB-only situation. It is also complex because it can result in a failure cascade.

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

  • Lists and Collection will simply be empty
  • The Array will contain five elements of Nothing
  • The somevar assignment will result in an immediate NRE because Nothing doesn’t have a .Text property

Referencing array elements later will result in an 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 code tries to use the array. This “silent exception” is detailed in this post. For our purposes, the key is that when 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 other things can be left uninitialized.

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 they are:

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 the form level, but initialize them in form load event handler when the controls do exist. This can be done in Sub New as long as your code is after the InitializeComponent call:

' 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

The array code may not be out of the woods yet. Any controls which are in a container control (like a GroupBox or Panel) will not be found in Me.Controls; they will be in the Controls collection of that Panel 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 an NRE will result when you attempt to reference it.

These should be easy to find now that you know what you are looking for:
VS shows you the error of your ways

“Button2” resides on a Panel

Remedy

Rather than indirect references by name using the form’s Controls collection, use the control reference:

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

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 bars
End 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 return when someCondition = False will result in an 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 same as 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:

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

This is a case of an object not being created as expected, but also demonstrates the counter usefulness of an empty 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.)

Remedy

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.

Remedy

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

If getFoo IsNot Nothing Then...

Controls

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.

Remedy

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.

Remedy

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.

Remedy

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

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


You probably forgot the New operator.

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

I took my ‘first steps’ into Google’s Comic-Con Rewards Lab with four fantastic experiences


San Diego Comic-Con is in full swing, and Google is back with another fun experience for attendees. Last year, the company had a whole Ferris wheel setup, but this time around, the experience is much more immersive, thanks to a collaboration with Monopoly Go! and Marvel’s “The Fantastic Four: First Steps,” which hits theaters on July 25.

Visitors will be able to take their first steps into the Google Play Rewards Lab, with unique experiences related to each of the members of the Fantastic Four. However, Google also has some rewards for members who aren’t able to experience the Rewards Lab in person.

Taking your first steps

Multiple pods and walkways at Google's San Diego Comic-Con Rewards Lab

(Image credit: Derrek Lee / Android Central)

The Google Play Rewards Lab was all about letting you experience what it’s like to be a member of the Fantastic Four. You step onto a conveyor belt that leads you into each of the four pods with four very different experiences.

6 features from other skins I want on One UI


Samsung Galaxy Z Flip 7 home screen One UI 8

C. Scott Brown / Android Authority

One UI has been with us for six years now, and it’s easily the best Android skin Samsung has made. One UI is smoother, more reliable, and easier to use than Samsung Experience or TouchWiz, the skins that preceded it. Aside from a blip with One UI 7, it’s been updated quicker than ever, often beating other Android skins.

The features One UI delivers have made it my favorite flavor of Android since I first used it on my Galaxy S10 Plus, but there are still things I’d like to change. Motorola, OnePlus, and others have added exciting features to their Android skins, and I’d love to see some of them adopted by Samsung in the next version of One UI.

Which of these featurs would you like to see most on Samsung phones?

15 votes

Motorola: Intuitive gestures

It’s hard to believe it’s been twelve years since the original Moto X hit shelves. That phone, along with the Moto G, shaped Motorola’s future over the following decade, and one of the best things it introduced is what the company now calls Kinetic Gestures. The ones I want most are the two that started it all — Fast Torch and Quick Capture.

On a Motorola phone, performing a double karate chop toggles the torch on or off, something that’s incredibly useful when you’re fumbling with keys in the dark and need to add some light to the situation. I use this a lot on my 2023 Razr Plus, where this gesture is much faster than unlocking the phone and swiping through quick settings.

Quick Capture opens the camera or switches between the front and rear lenses if the camera is already open. This gesture requires a double flick of the wrist, and once you get used to it, it’s the easiest way of quickly launching the camera so you don’t miss an important shot.

Motorola: Easy customisation

One UI has plenty of theming options, more than Motorola does, but it’s all split across too many different menus and apps. Theming icons is in Theme Park, fonts are in the settings menu, and the Material You colors are in a menu accessed from the home screen. It’s even worse on Samsung’s Z Flip series, where all of the options for the cover screen are spread across even more menus. It adds too much friction to customising your Samsung phone.

Motorola has gone about things in a simple, thoughtful way. All of the options for themes, icons, fonts, home screen grid sizes, and the cover screen are in a single place. Long-press the home screen, open the personalise menu, and there are all of the options you could ever need. Sure, I miss some of the more advanced tweaks from One UI, but Motorola’s approach of listing everything together is more approachable for users.

Pixel: Now Playing

Google Pixel 9a now playing history

Ryan Haines / Android Authority

Now Playing is one of those small features that you don’t think about until you use a phone that doesn’t have it. I used a Pixel 9 Pro as my daily phone recently, the longest I’d used a Pixel since I owned a 3XL, and it reminded me how many subtle quality of life features you get on Pixels. Knowing what song is playing in the background wherever I am, without having to ask my phone to do it, is more convenient than the alternative.

The Now Playing history is great, too. I’ve planned to listen to a song that I’ve heard and searched for when out and about, only to forget what the song was by the time I get home. Now Playing keeps a history of the songs it hears, so I don’t have to rely on my memory.

Pixel: Call Screening

Google Pixel 8a call screening

Andy Walker / Android Authority

Pixel 8a

Call Screening debuted on the Pixel 3 in 2018, but I never got to experience it as it didn’t come to the UK until 2021. When I used it with the Pixel 9 Pro recently, I couldn’t believe how much better it is than Samsung’s alternative. Samsung’s Call Assist can do the basics of screening calls, transcribing the conversation, and live translation. But it’s the extras that Google has added to Call Screening over the years that Samsung can’t keep up with.

Call Screening on Pixels can wait on hold for you and notify you when the person you’re calling comes back, tell you how long the average wait time is for a call to a business, and even map and label phone tree options. Samsung is off to a good start with Call Assist, but there’s a lot more work to be done.

OnePlus: Screenshot pixelation

One plus image pixel

Zac Kew-Denniss / Android Authority

I take a lot of screenshots in this line of work, and I often need to censor things like my email, address, and other personal information. One UI does have a blur and pixelation tool in the gallery, but it’s a manual process that can be quite messy if you don’t have an S Pen to make things easier. OnePlus and Oppo devices have an AI-powered auto mode that applies a neat blur to what it identifies as sensitive information.

It isn’t perfect. In the example above, I had to censor two elements that it missed manually, but that was much less painful than having to do the whole thing myself, and features like this will only improve with updates.

OnePlus: Open Canvas

OnePlus debuted Open Canvas on the OnePlus Open, and since then, it’s come to many of the company’s devices. It’s a new approach to window management on mobile that is more intuitive and makes the most use out of the space available on a screen. Before OnePlus introduced this, One UI had my favorite multitasking system, but Open Canvas blows it out of the water.

Google has taken some inspiration from Open Canvas, adding a 90:10 split to multi-window that you can try in One UI 8 on the Fold 7, Flip 7, Flip FE, and the S25 series running the beta. It’s an improvement, but still doesn’t come close to what OnePlus is doing, and I’d love to try Open Canvas on a big screen, like my Galaxy Tab S10 Plus.

One UI 9 needs to impress

Galaxy S25 red black background

Zac Kew-Denniss / Android Authority

One UI 8 feels like a stop-gap update. One UI 7 made a lot of big changes to Samsung software, most of which were welcome, but the delayed and fragmented update rollout left a bitter taste. One UI 8 is shaping up to have a much smoother release, but there’s almost nothing new here to be excited about. It feels like One UI 8 received only minimal changes so that Samsung could push it out the door quickly and act as damage control for last year.

One UI 9, whenever we see it, needs to give us something to be excited about, and looking to other OEM skins for inspiration, drawing on what Motorola, Google, and OnePlus users love about their phones, would be a good place to start.

DOGE is reportedly pushing an AI tool that would put half of all federal regulations on a ‘delete list’


According to a report from The Washington Post, DOGE is using an AI tool to analyze federal regulations and determine which to get rid of. A DOGE PowerPoint presentation obtained by the publication notes that its “AI Solution” — reportedly called the DOGE AI Deregulation Decision Tool — found that 100,000 out of over 200,000 regulations “can be deleted.” The document sets a September 1 goal deadline for agencies to complete their own deregulation lists using the tool, which it says can be done in under four weeks, and then “DOGE will roll-up a delete list of 50% of all Federal Regulations (100k Regulatory Rules).”

The tool is targeting regulations that are no longer required by law, The Washington Post reports. After it makes its suggestions, staffers would review the proposed deletions before finalizing a plan. According to the PowerPoint, the tool has already been tried out by the Consumer Financial Protection Bureau (CFPB), where it’s been used to write “100% of deregulations,” and by the Department of Housing and Urban Development (HUD) for decisions on 1,083 regulatory sections. The Washington Post spoke to three HUD employees who confirmed it was recently used. One also said that the tool got things wrong on several occasions, misreading the language of the law at times.

DOGE will reportedly start training other agencies on the tool this month. Head over to The Washington Post to read the full report.

U.K. starts enforcing online age check rules


A U.K. law requiring that pornography websites verify the age of their users took effect Friday.

The BBC reports that around 6,000 porn sites have said they will start verifying users’ ages to comply with the Online Safety Act, although at least one major site was not requiring age checks as of Friday morning.

The law also requires that online platforms prevent children from being exposed to harmful content, which is why sites like Reddit, Bluesky, X, and Grindr have also begun asking users in the U.K. to verify their age through means including selfies or government-issued IDs.

This is just one of a number of new child protection laws that could normalize online age checks globally, according to Wired. The approach has been criticized by groups such as the Electronic Frontier Foundation as a threat to online privacy and anonymity — indeed, it’s worth noting that in a recent breach of the dating safety app Tea, many of the affected images were selfies and digital IDs uploaded for account verification.

Some internet users may try to get around age checks by using fake IDs, selfies of video game characters, or VPNs.

Build an AI Agent from scratch with CrewAI and Clarifai


AI agents are software systems designed to reason, plan, and act toward achieving defined goals. They move beyond simple automation by making decisions, adapting to changing information, and coordinating multiple steps to complete complex tasks.

The operational effectiveness of AI agents is underpinned by several core principles:

At their core, agents use Large Language Models (LLMs) as their reasoning engine. However, the true capability of an agent comes from combining this intelligence with these supporting components, enabling them to act effectively in dynamic, real-world environments.

While LLMs provide the reasoning power for agents, they need structured approaches to handle complex tasks effectively. This is where agentic design patterns come in. These are proven strategies that guide agents to reason, act, and improve over time.

Here are three of the most common and effective patterns for building practical agents:

These patterns are often combined. For example, a multi agent system may use ReAct for individual agents while employing Reflection at the system level to refine outputs. Together, they form a foundation for building more capable, reliable, and transparent agents that can tackle increasingly complex tasks.

Now, let’s build a simple AI agent from scratch.

Building an AI Agent from Scratch

Let’s put everything together by building a simple agent using Crew AI. For this example, we’ll create a blog-writing agent that can research topics, gather information, and generate well-structured content.

Step 1: Define Tools

A tool is a function that an agent can call to perform actions. Tools expand what the model can do — fetching real-time data, querying APIs, summarizing documents, or even publishing results.

Every agentic framework provides some predefined tools for common tasks such as web search or file operations, but for specific workflows you often need to define custom tools. In the case of a blog-writing agent, the first step is being able to gather research material for a given topic.

Here’s a simple custom tool that does that:

This is a simple example for demonstration. In a real-world setup, the fetch_research_data function would call an external API (like a web search service or knowledge base) or scrape trusted sources to return actual, up-to-date research.

With this tool in place, our blog-writing agent will be able to collect background material before drafting any content.

Step 2: Select and Configure the Language Model

Large language model (LLM) is the reasoning core of our agent. It processes inputs, breaks down tasks, and generates structured outputs. For a blog-writing agent, this means analyzing research material, drafting outlines, and creating coherent content that aligns with the topic.

Not all models are equally suited for this. For agentic workflows, it’s best to use models that are optimized for reasoning and capable of working with tools. While large foundational models provide strong general performance, smaller or fine-tuned models can be more efficient and cost-effective for specific tasks like content generation.

Clarifai provides a variety of models accessible through an OpenAI-compatible API, making it easy to integrate them into an agent’s workflow. For this blog-writing agent, we’ll use DeepSeek-R1-Distill-Qwen-7B.

Before configuring the model, you’ll need to set your Clarifai Personal Access Token (PAT) as an environment variable so the API can authenticate your requests.

Here’s how to configure it:

This configuration connects our agent to the DeepSeek-R1-Distill-Qwen-7B model using the OpenAI-compatible endpoint. In production, you could easily swap this model for another depending on your content needs — for example, a larger model for more complex reasoning or a smaller one for faster drafts.

With this setup, our blog-writing agent now has a functional core that can process research inputs and turn them into structured, well-written content.

Step 3: Create the Agent, Task, and Crew

With our research tool defined and the model configured, we can now assemble the core components of our system:

  • Agent: The intelligent entity with a defined role, goal, and backstory.

  • Task: The specific work we want the agent to accomplish.

  • Crew: The orchestrator that manages agents and tasks.

For our use case, we’ll create a blog-writing specialist who can gather research, analyze it, and generate a structured draft.

In this setup:

  • Agent: We define a blog writing specialist with a clear role, goal, and backstory. This agent uses the fetch_research_data tool to gather information before drafting the blog.
  • Task: We create a well scoped task describing what needs to be produced: a comprehensive blog post on “The Future of AI Agents” that covers trends, breakthroughs, and real world applications. The expected output is a complete markdown formatted draft.
  • Crew: We bring the agent and task together into a Crew that handles execution. While this example uses only one agent, the same structure can easily scale to multi agent projects.

With these components in place, the agent has everything it needs: a clear purpose, the right tools, and an actionable task to deliver a well structured, high quality blog draft.

Step 4: Run the Agent

To execute our setup, we call project_crew.kickoff(). This method triggers the full workflow — the agent interprets the task, uses the research tool to gather insights, reasons through the information, and generates a complete blog draft.

Here’s the entire code:

If you are looking to build and deploy your own custom MCP servers, check out our detailed blog tutorial here. Once built, these MCP servers can be integrated as tools within your AI agents, enabling you to create MCP-powered agentic applications. We’ll dive deeper into this integration in upcoming tutorials.

Conclusion

In this guide, we covered what AI agents are, their key components and design patterns, and built a blog-writing agent using a Clarifai-hosted reasoning model, showing how tools, memory, and reasoning work together to create dynamic, goal-driven systems.

That said, it’s important to remember that agents are not always the right choice. When building applications with LLMs, it’s best to start simple and only add complexity when it is needed. For many use cases, workflows or even well-structured single LLM calls with retrieval and in-context examples can be enough.

Workflows are predictable and consistent for well-defined tasks, while agents become valuable when you need flexibility, adaptive reasoning, or model-driven decision-making at scale. Agentic systems often trade off latency and cost for better task performance, so consider where that tradeoff makes sense for your application.

If you want to dive deeper into building more advanced applications, explore more AI agent examples in the GitHub repo. Check out the documentation to learn how you can build with other agent frameworks such as Google SDK, OpenAI SDK, and Vercel AI SDK.



All Mystery Gate Riddles In Wuchang: Fallen Feathers



GameSpot may receive revenue from affiliate and advertising partnerships for sharing this content and from purchases through links.

How do I wite unit tests for a visual c++ project which builds a .dll without a .lib – the suggested methods of writing unit tests require a .lib


I have a project which builds a plugin .dll for another program – no .lib is produced for this, despite having several exports. Note that I have very little control over how the exports are defined in the main executable’s header.

I want to write unit tests for it, but honestly, trying to write them by calling via the small number of API calls implemented would be massively unproductive. So I thought I’d link with the generated object files as suggested in a few places.

But I can’t.

The unit test project that visual c++ helps you to create expects you to provide a .lib file. However, the build does not provide a .lib file. I’ve seen various questions submitted about similar problems over the years – and none of the answers work. They suggest if you’re not exporting anything, a .lib file won’t be generated – well, I’m definitely exporting symbols.

Another answer to a similar question says I need to have a header which does

#ifdef MYPROJECT_EXPORTS
#define MYPROJECT_API __declspec(dllexport)
#else
#define MYPROJECT_API __declspec(dllimport)
#endif

and use MYPROJECT_API in the source.

So I did that. It had absolutely no effect.

Some answers say there’s an ‘export symbols’ in the project properties – not that I can find, there isn’t (though searching project properties isn’t all that easy, so I could have missed it).

A couple of things have suggested I should use import libraries. But I don’t import any libraries.

So I’m a bit stuck.

Google’s AI Summaries Really Do Cut Website Traffic, Study Finds


In 2024, Google began adding AI-generated summaries to the top of its search results page. Online publishers have since reported drops in website traffic, saying the summaries are replacing traditional search results by allowing users to rely on AI responses instead of visiting individual websites.

A recent Pew Research Center report analyzed the browsing activity of 900 adults in the US. Of them, 58% received an AI-generated Google summary while using the search engine. When they did, participants were almost half as likely to click on links to other websites; only 8% did, compared to 15% users who clicked through linked results when an AI summary did not appear. Even the links shown within the AI summaries themselves got very few clicks, with just 1% of such results leading to a source being opened.

Searches written as questions, those using longer phrases, and searches in full sentences were more likely to have AI summaries. Only 8% of brief queries (one or two words) had AI summaries, but that figure rose to 53% when the search included 10 words or more. In total, about 18% of all searches in the study had an AI-generated result.

Pew’s study demonstrates that Google’s AI overviews are lowering the chances that users will click on links to external websites, like the one you’re on right now. Wikipedia editors’ worst fears have come true.

Devotional: Are You Crying Out To God?


Sometimes it’s hard to keep your head up, isn’t it?

When days seem to run together, the same old things happening day after day, it is difficult to stay positive.

I’ve noticed, though, encouragement can come from the smallest of places. 💯

A quick hug from your youngest, with a whispered, “I love you, momma.”

A comment by your husband as he returns home from work about how nice the house looks. 

A thank you from a friend, who called you crying because she needed to talk about bad news she received that morning.

Or, just looking out the window at the beautiful blue sky and warm sunshine, realizing that God is TRULY great and that He wants us to have peace! 🙌

Some days we can wake up encouraged, and our days are rosy and wonderful. Other days, we have to look hard for encouragement. Those are the kinds of days David had when he wrote Psalm 42:5-11.

Have you had days where you were crying out to God? I have. And God answers – EVERY TIME. It may not be immediately. It may not be in the way you expect. BUT HE DOES ANSWER! Psalm 34:18.

On those days when you feel discouraged, look outside yourself. Look around at all you have – your husband, your children, your home. Looking at what to be grateful for will lift your spirit and help you realize all that you DO HAVE, rather than focusing on what you DON’T.

Be sure to pick up a copy of my Gratitude Prompts Binder as well. It asks you a lot of deep and meaningful questions, specifically designed to get your heart super happy and thankful.

Remember…

When you pass through the waters, I will be with you; and through the rivers, they shall not overwhelm you; when you walk through fire you shall not be burned, and the flame shall not consume you. – Isaiah 43:2