What is the difference between = and: =

I am sure it is simple, but I can not find the correct line to get the result of Google. In VB.NET, what is the difference between = (equal sign) and: = (colon followed by an equal sign)?

+6
source share
3 answers

The operator: = is used to pass arguments by name to VB.Net. For example, 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 used here, I have passed the values ​​out of order. But since I bound the arguments by name using: =, the compiler will pass values ​​correctly.

The = operator is context sensitive in VB.Net. This can be either an assignment operator or a comparison operator. For example,

 Dim x = 42 ' Assignment if x = 36 Then 'Comparison above End if 
+16
source share

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

  a = 5 

Comparison example

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

.: = is used specifically for calling functions with setting specific parameters to a 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 

Usually you call a function as follows:

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

But you can also call the function as follows:

 Call studentInfo("Mary", birth:=#9/21/1981#) 
+3
source share

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

Compare: If 7 = 7 Then ...

Set: Dim myInt As Integer = 7

Let's 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) 

Sometimes it is easier to read the constructor when you know what values ​​you are setting, especially if you have a constructor like SomeConstructor(12, 432, True, False, 32)

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

There are probably more, but this is what I got off my head.

+2
source share

All Articles