user2718511
user2718511

Reputation: 1

VB.Net initializing datasets

When did Microsoft start forcing datasets to be initialized with a "New" statement? My company has a website that was started many years ago and a lot of the datasets were declared with a statement like

Dim someDataset as Dataset = Nothing

This code has worked for a long time but we recently started receiving errors stating Value cannot be null. Parameter name: dataset.

I've done my best to update this old code but I'm not aware of any updates to the libraries we are using and I'm trying to identify what triggered this error to begin with. Thank you

I'd like to emphasize that no changes were made to the code before the error started occurring as unlikely as that might sound. It is a large app and datasets are used throughout it in a variety of ways. It has been in production for many years and worked as expected before this error started occurring recently.

Upvotes: 0

Views: 3341

Answers (2)

Karl Anderson
Karl Anderson

Reputation: 34834

There is a difference between declaring and instantiating.

This line declares a DataSet:

Dim myDataSet As DataSet

Note: Since you only declared a DataSet object, it is not set to an instance, therefore it is Nothing.

This line instantiates a DataSet:

myDataSet = New DataSet()

Often you will see the lines put together, like this:

Dim myDataSet = New DataSet()

If you only declare a DataSet, then you must be sure to check if it is Nothing before you use it, like this:

If myDataSet Is Not Nothing Then
    ' Use myDataSet because there is an instance of it
End If

Note: You should ALWAYS check if the return type of a Function is Nothing or not.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152654

That has not changed since Day 1 of .NET. All reference types must be created with a New statement somewhere or else they will remain a null reference (Nothing).

It sounds like some other part of the app that used to create the dataset has been removed or changed so that it sometimes returns Nothing.

Upvotes: 1

Related Questions