views:

1280

answers:

2

Is it necessary to use "Nothing" keyword to initialize a DataSet in VB.NET?

+5  A: 

Well if you set the variable to "Nothing" then you're not initialising an actual DataSet object at all - you're just setting the value of the variable to a null reference.

For an instance or static variable, Nothing will be the default value. For a local variable, in C# there's effectively no default as the compiler doesn't let you use a variable without it being definitely assigned - whether the VB compiler lets you get away with this or not depends on compiler settings. However, if it does let you use an unassigned variable, the value will be Nothing by default.

Jon Skeet
Option Strict isn't used for this (it's there to enforce strict type semantics to restrict implicit type conversions). There is a compiler option, though, that lets you specify uninitialised variables as errors, warnings, or neither.
ChrisA
Thanks Chris - will update answer to reflect this.
Jon Skeet
+3  A: 
Dim ds as New DataSet

(or, if it's already defined, ds = New DataSet) ... is all you need to initialise an actual DataSet object. It's the use of the 'New' keyword that creates the object. Later on, after it has some DataTables in it, you can clear them out with

ds.Tables.Clear

As Jon says,

Dim ds as Dataset = nothing

... does not create an instance of a DataSet, initialised or otherwise. All it does is define 'ds' as a variable that must refer to an instance of the DataSet class, and explicitly sets it to point to nothing.

Dim ds as DataSet

.. would achieve the same thing. Again, later on, after you've used your DataSet,

ds = Nothing

... does not reinitialise the DataSet, all it does is set your variable 'ds' to no longer refer to anything.

ChrisA