Rami Alshareef
Rami Alshareef

Reputation: 7160

Whats the Difference between (As) and (=) in object declaration in VB.NET

I can create a new object like this:

Dim sqlconn As New SqlClient.SqlConnection(cs)

or like this:

Dim sqlconn = New SqlClient.SqlConnection(cs)

What's the difference? Since both worked fine for me!

Upvotes: 8

Views: 603

Answers (1)

Guffa
Guffa

Reputation: 700720

The first one is the short form of:

Dim sqlconn As SqlClient.SqlConnection = New SqlClient.SqlConnection(cs)

The second one depends on what version of VB you are using. In VB 7 and VB 8 it is the same as:

Dim sqlconn As Object = New SqlClient.SqlConnection(cs)

In VB 9 type inference was introduced, so the compiler will infer the type from the assignment and produce the same code as the first one.

The type inference requires that the option Option Infer is set to on. This is the default setting, but it might be off if you migrate a project from an older version.

Upvotes: 14

Related Questions