tags:

views:

206

answers:

3

I'm sure this is straightforward but I cannot find the correct string to get a google result. In VB.NET what is the difference between = (equals sign) and := (colon followed by equals sign)?

+1  A: 

= is a comparison AND a set operator, but:= is just a set operator.

Compare: If 7 = 7 Then ...

Set: Dim myInt As Integer = 7

Say you have a custom object called SuperList whose constructor takes a variable called initialCount, then you can do things like:

Dim myList As New SuperList(initialCount:=10)

It's just sometimes easier to read a constructor when you know what values you're setting, especially if you have a constructor like SomeConstructor(12, 432, True, False, 32)

It makes more sense to see SomeConstructor(monthsInYear:=12, daysInYear:=432, leapYears:True, leapDays:=False, daysInMonth:=32)

There's probably more but this is what I got off the top of my head.

Cory Larson
but in vb.net = is both a set and comparison operator
Jason Irwin
Your opening statement is incorrect
Binary Worrier
Edited... My Bad.
Cory Larson
Better, but ":= is an operator used to set the values of sub and functions arguements" would be better, but then it's not my answer :) I removed my downvote.
Binary Worrier
Thanks Binary, I think I jumped into its usage more than focusing on the definition -- I'll be more careful from now on.
Cory Larson
+13  A: 

The := operator is used to pass arguments by name in VB.Net. For instance take the following code

Sub Foo(p1 As integer, p2 As String)
  .. 
End Sub

Sub Test()
  Foo(p2:="foo",p1:=42)
End Sub

If you look strictly at the types involved here I've passed the values out of order. But Because I bound the arguments by name using :=, the compiler will properly pass the values.

The = operator depends on the context in VB.Net. It can be either an assignment or comparison operator. For instance

Dim x = 42 ' Assignment
if x = 36 Then 
 'Comparison above
End if
JaredPar
Good to know, thank you!
Jason Irwin
+3  A: 

The equal sign is used for assignment and is also a comparison operator. An example of assignment is

  a = 5

An example of comparison is

  if (a = 5) then
    ' do something here
  end if

The := is used specifically for calling functions with setting particular parameters to the value by name. For example:

Sub studentInfo(ByVal name As String, _
       Optional ByVal age As Short = 0, _
       Optional ByVal birth As Date = #1/1/2000#)

  Debug.WriteLine("Name = " & name & _
                "; age = " & CStr(age) & _
                "; birth date = " & CStr(birth))
End Sub

Normally, you would call the function like this:

Call studentInfo("Mary", 19, #9/21/1981#)

But you can also call the function this way:

Call studentInfo("Mary", birth:=#9/21/1981#)
Tommy Hui