What is the difference between declare datatable class with () and without ()

Viewed 49

I have a question about declaring a datatable variable.

Is there any difference if I declared a datatable variable as:

Dim xDt as new datatable

or

Dim xDt as new datatable()

??

1 Answers

Firstly, you're not declaring a class there. You are declaring a variable of type DataTable. The declaration is irrelevant anyway. What matters is that you are creating an instance of the DataTable class by invoking a constructor with the New keyword. A constructor is just a special method and, in VB, you can omit the parentheses when calling a method without arguments. This:

Dim table As New DataTable

is functionally equivalent to this:

Dim table As DataTable = New DataTable

which is functionally equivalent to this:

Dim table As DataTable

table = New DataTable

As you can see there, the last line is what matters and the variable declaration is irrelevant. That last line is equivalent to this:

table = New DataTable()

Whether you include the parentheses or not is up to you but I would suggest that you pick an option for a logical reason and stick to it consistently.

Personally, I always include parentheses on standard method calls but I always omit them from constructors. I do the former to make methods easily distinguishable from properties, so I would do this:

Dim str = obj.ToString()

rather than this:

Dim str = obj.ToString

With constructors though, there's little risk of mistaking them for properties but there is some risk of mistaking them for arrays, e.g.

Dim tables As DataTable()

Declares a variable of type DataTable array without creating an object while this:

Dim table As New DataTable()

declares a variable of type DataTable and assigns a new object to it. In my opinion, omitting the parentheses on constructors reduces the likelihood of confusion while including it on other methods does the same.

Related