What does a := (colon equals) in VB.NET do? [duplicate] - vb.net

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the use of the := syntax?
I've tried hunting down the MDSN documentation for := in VB.NET as well as scoured Google only to be linked to a dead MSDN page... What would the purpose of := be?

It strongly names arguments, allowing you to call a method with arguments in an order other than that specified in the method definition.
For example:
sub foo (byval x As Long, byval y As Long)
debug.print (String.Format("{0}, {1}", x.ToString, y.ToString))
end Function
can be called with the order of the arguments reversed by using their names:
foo (y:=999, x:=111)
prints:
111, 999
This is especially useful when you have a long list of optional arguments, you only want to specify a few of them, and those that you want to specify are not the first ones.

It's used to name arguments in a method call and is usually used with optional arguments.
It's especially useful for calling Word or Excel methods through ActiveX calls, where there are an awful lot of optional arguments, most of which are never used.

Assigns values by names instead of position.
Given
Private Function foo(arg1 As Integer, arg2 As Integer) As Boolean
Debug.WriteLine("{0} {1}", arg1, arg2)
Return True
End Function
these produce the same result
foo(arg2:=2, arg1:=1)
foo(1, 2)
debug output
1 2
1 2

I am not sure about VB.NET, but in Visual Basic 6.0 that was the syntax for assigning a value to method parameter by name rather than by ordinal position.

Related

Differences in the way of writing lambdas in VB

So I've been reading up on lambdas in VB recently and am a bit confused tbh. I've got the code running properly, but want a better understanding. My main question is the use of the Invoke() method and the way of declaring a lambda.
One method I've seen is this:
Dim increment2 = Function(x)
Return x + 2
End Function
and the other:
Dim func1 As Func(Of Integer, Integer) =
Function(value As Integer)
Return value + 1
End Function
My question is, what's the difference? And what role does the Invoke() method play. I've seen to ways of calling lambdas, one like func1(4) and the other is func1.Invoke(4).
I should mention, that regardless of what change I make the output remains the same (5), leading me believe the change is something not very noticeable. And I'm curious as to what it is.

Option Strict On disallows late binding in vb.net

I'm using COM interface to 3rd part program to get information with my functions. (VS2017 and Framework 4.7.2).
I'm getting an error from Visual Studio: "Option Strict On disallows late binding" for the below function
'x, y, z, al, be, ga. as an array
Protected Friend Shared Function GetComputedBRFPos(ByVal bodyElement As IScrBody, ByVal index As Integer) As Array
Return bodyElement.getComputedBRFPos(p_index:=index)
End Function
It has a documentation at 3rd part tool i'm also writing the description.
VARIANTList getComputedBRFPos ()
Get current BRF position, creates an implicit solver if no solver is existing. Array elements: x, y, z, al, be, ga.
For an example i'm putting another function i'm using and getting no late binding error for below function.
Protected Friend Shared Function Get_sb_node_pos(ByVal bodyElement As IScrBody, ByVal childIndex As Integer) As Array
Return bodyElement.get_sb_node_pos(p_childIndex:=childIndex)
End Function
And it's description at documentation.
VARIANTList get_sb_node_pos (int childIndex)
Get all elements of
sb_node_pos as an array.
I think it causing for bodyElement.getComputedBRFPos(p_index:=index) "index" value but i don't know what's the exact problem and how to achieve.
From the documentation you posted, it seems like bodyElement.getComputedBRFPos doesn't take any parameters. In VB.NET, the () are optional for method without parameters. So your code end up looking like this.
Return bodyElement.getComputedBRFPos()(p_index:=index)
Which doesn't return an array but instead return an element of the array which is of type object.
You should remove the parameter, change the return type or show us the documentation of the method with the parameter you are trying to call.
Return bodyElement.getComputedBRFPos()

Chance of breaking existing code by adding optional parameter to VB.NET function?

Is there a chance that existing code in a large project might bomb if I add a new optional parameter to a function that's used everywhere? I know I can overload the function instead and minimize the risk, but really.. what's the risk if I insist on going with an optional parameter?
Here's an example:
Public Function GetContent(ByVal URL As String, ByVal ID As String, Optional ByRef PageTitle As String = "") As String
Try
Dim web As New HtmlWeb()
Dim doc As HtmlDocument = web.Load(URL)
ID = "//div[#id='" & ID & "']"
Dim ContentNode As HtmlNode = doc.DocumentNode.SelectSingleNode(ID)
' The two lines below are the mere extent of what's new inside this function, besides the new Optional ByRef parameter in its signature
Dim PageTitleNode As HtmlNode = doc.DocumentNode.SelectSingleNode("//title")
If Not PageTitleNode Is Nothing Then PageTitle = PageTitleNode.InnerHtml
Return ContentNode.InnerHtml
Catch ex As Exception
Return "<h4> Bad. Very bad. </h4>"
End Try
End Function
PS: I'd like to comment on my question after the fact, having read others' responses below and having done some additional research myself. Originally, I didn't want to question the validity of the approach of using an optional parameter. That was something VB.NET was allowing me to do and I felt I had every right to use--besides that it was simply very convenient! But my original question had more to do with whether there may be gaps in how optional parameters are implemented, from compilation down to execution--gaps that I should consider as I design my code. I was unaware of the historical significance of the optional parameter approach in relation to the overload approach. I've learned now that it's not that there are gaps or flaws in the optional parameter approach; rather, it was a solution designed for a different and older set of concerns that was simply overridden with the advent of the Common Language Runtime. I'm using VS2013. Sure, everything compiled fine with the optional parameter approach and seemed to run fine but I wanted to confirm I wasn't potentially breaking something else by adding an optional parameter--especially since someone looked at my code and suggested I should overload the function instead. I wanted to prove why I shouldn't keep my optional parameter method. James Thorpe answered that question for me now, I think. But as Tim Schmelter asked, is there a benefit for doing it this way (optional parameters) as opposed to the overload approach? To me now the overload approach seems the best and only way, and that is because I'm using a newer set of technologies that the optional parameter approach--which was implemented for Microsoft's older Component Object Model, or COM--simply wasn't designed to address (see page 83 of the book, "Microsoft Visual C# 2013 Step By Step" by John Sharp). Particularly now, if there are external modules expecting to find the old function signature (i.e., the function parameter layout that existed before I added the new optional parameter), they'll break unless I recompile them too! That's a hindrance for me. But overloading handles this software development problem much better without need for recompilation, something only now supported by the newer Common Languange Runtime, or CLR. I suppose the optional parameter support in VB.NET is more of a historical holdover now from the old COM days--and not the very best solution for my specific requirements. I've also just learned that, "The Common Language Specification, which defines the subset of the CLR that all languages should support, explicitly disallows a reliance on optional parameters. This means they are not a candidate for use in the Base Class Library and will probably never been seen in any of the other libraries shipped as part of the .NET Framework." (from the online article, "Optional Parameters Are Gaining Ground in .NET", by Jonathan Allen). Although the rules are laxer for us regular developers that consume Microsoft technologies, I think there's something to be said for their internal decision not to rely on optional parameters. I just wanted to post and share that with you in case like me you've also come here wondering!
Within a single project? No, it should be fine. However, in the comments you said:
Let's say there were other projects calling it (there is a possibility). Would it break those if I didn't rebuild them?
Optional parameters are actually baked in at compile time, so if you have your original method signature:
Public Function GetContent(ByVal URL As String, ByVal ID As String)
And someone is calling it thusly:
GetContent(someUrl, someId)
It will be compiled into their assembly as-is. With your new optional parameter, anything calling it as above without passing in the parameter would actually get compiled as:
GetContent(someUrl, someId, "")
Note how the default value of the optional parameter has automatically been brought in. If you're rebuilding everything, it's all good. However, in those projects that are referencing this one that aren't rebuilt, they will have the original two-parameter call. Your GetContent method now requires 3 parameters at runtime - you'll get a runtime error as it can't find an overload of the function that still takes 2 parameters.
Here's how you can do it without breaking code...
Public Function GetContent(ByVal URL As String, ByVal ID As String, ByRef PageTitle As String = "") As String
' the rest of your function here
End Function
Public Function GetContent(ByVal URL As String, ByVal ID As String) As String
Return GetContent(URL, ID, "")
End Function
That way you have a version of the function with 2 parameters for the existing code and one with 3.
If you want to encourage programmers to switch to the 3 parameter version, then you can mark the 2 parameter version like this:
<Obsolete("Use the version that takes pageTitle as a 3rd parameter">
Public Function GetContent(ByVal URL As String, ByVal ID As String) As String
Return GetContent(URL, ID, "")
End Function
That will give you a compiler warning if you try to call the 2-parameter version.

How do I pass parameters to a method both as normal and like a property?

In RealBasic (now Xojo), which I'm leaving to the past, I used to be able to declare a method like this:
Sub MyCoolSub(param1 as string, Assigns parameter2 as integer)
Do
'Waste CPU time scrying the universe.
Loop
End Sub
And then call it in this way:
MyCoolSub("Answer")=42
Now I'd want to replicate this behaviour in VB.Net.
The closest thing I stumbled upon is the Property's clauses, but VS does not let me add parameters to it that would however require some overhead which decreases the convenience of this type of declaration.
Do you have any better suggestion?
PS. As a side question I would be pretty happy to know that there is a way to comment with "//" in VB.Net, as I'm not that comfortable with the apostrophe character. Is there any thing as a VS comment characters list? Maybe an extension could do it...
When I look at the documentation for the Xojo Assigns keyword the closest thing I can think of is to create a write-only property like this:
Public WriteOnly Property theVolume(a As Integer, b As Integer) As Integer
Set(c As Integer)
Debug.WriteLine("a={0}, b={1}, c={2}", a, b, c)
End Set
End Property
theVolume(1, 2) = 3
a=1, b=2, c=3
Regarding your "P.S." note:
to ease your switching to VB.NET you can use the following AutoHotKey command:
:O://::'
This will do the appropriate substitution for you during typing.
You can limit it only to your IDE window using #IfWinActive directive.
Anyway, Roslyn VB.Net compiler is now open source so you can download and play...

VB.NET - What does ":=" do?

I can't find any information online or under the Operator documentation, but I've seen this ":=" used a few times in VB.NET and I can't work out what it does.
It's used for named parameters (ht to SLaks for the link) in a method call and is usually used with optional arguments.
It's usually useful for calling Word or Excel methods through ActiveX calls, where there are an awful lot of optional arguments, most of which are never used.
Example
Private Function test(arg1 As Integer, arg2 As Integer) As Boolean
Debug.WriteLine("{0} {1}", arg1, arg2)
Return True
End Function
These two will both produce the same result
test(arg2:=2, arg1:=1)
test(1, 2)
Debug output
1 2
1 2
This is used for named parameters:
MyMethod(parameterName := value)
This is to use "named parameters", so you can use parameters in a function in any order, telling the function the name of each one. :)