VB.Net calling New without assigning value - vb.net

In C# I can do this:
new SomeObjectType("abc", 10);
In other words, I can call new without assigning the created instance to any variable. However, in VB.Net it seems I cannot do the same thing.
New SomeObjectType("abc", 10) ' syntax error
Is there a way to do this in VB.Net?

The following works on the Mono VB compiler (vbnc, version 0.0.0.5914, Mono 2.4.2 - r):
Call New SomeObjectType("abc", 10)
Notice the required Call.

See the answers to this other SO Answer
So this should work:
With New SomeObjectType("abc", 10)
End With

One can define a Sub to discard the constructed object:
Sub gobble(dummy As Object)
End Sub
Then call the constructor as follows:
gobble(New SomeClass())
I'm using this approach in tests when I test exceptions in constructors. I construct the object in a lambda and pass that lambda to a function that checks for the Exception. Fits nicely on a line.
assertThrows(Of ArgumentOutOfRangeException)(Sub() gobble(New ClassUnderTest("stuff")))

That should be the correct syntax, e.g.
Dim name As New String
Dim url As New Uri("http://www.somedomain.com")
Have you got some more code where this is happening?

Related

type var is not defined vb.net

I found an example in C# and from my understanding there is no alternative to 'var' in VB.NET. I am trying to create a datatable that will populate depending on a LINQ command further down in my code that calls this function. I have searched for a solution, but unable to find anything that works. Any assistance on what I should use would be appreciated. Note that I do have both Option Strict and Option Infer on as well.
Private Shared Function ToDataTable(rows As List(Of DataRow)) As DataTable
Dim table As New DataTable()
table.Columns.Add("Title")
table.Columns.Add("Console")
table.Columns.Add("Year")
table.Columns.Add("ESRB")
table.Columns.Add("Score")
table.Columns.Add("Publisher")
table.Columns.Add("Developer")
table.Columns.Add("Genre")
table.Columns.Add("Date")
For Each row As var In rows
table.Rows.Add(row.ItemArray)
Next
Return table
End Function
C# uses 'var' for implicit typing - VB uses Option Infer On combined with omitting the type.
The VB equivalent is:
Option Infer On
...
For Each row In rows
table.Rows.Add(row.ItemArray)
Next row
.NET already has .CopyToDataTable extension for that:
Dim table As DataTable = rows.CopyToDataTable
The VB equivalent is simply Dim, without any strong typing.
Dim sName = "John Henry"
In this example, the compiler infers type String (when Option Infer is set to On).
In your example, you may omit the As var portion. The compiler will infer type DataRow.
Tag your questions well, in this case there is no C# issue. Your problem is your are not writing an actual type on the foreach statement. This will fix it:
For Each row As DataRow In rows
table.Rows.Add(row.ItemArray)
Next

VB.NET GetProcessesByName method is missing

I'm building a program in VB whose purpose is to run in the background and automatically update other programs I've created. To do this, it has to check if those programs are still running and, if they are, wait for them to close.
Unfortunately, the program won't compile. The exception states: GetProcessesByName is not a member of String. (The string it refers to is the Process parameter shown in the code below.)
I can't understand why this is happening, because this method has always worked without problems. I'm using Visual Studio 2015. For your reference, here's the code block:
Private Function CheckIfRunning(Process As String) As Boolean
Dim MyProcess() As Process
MyProcess = Process.GetProcessesByName("ProcessName")
If MyProcess.Count > 0 Then
Return True
Else
Return False
End If
End Function
Try using System.Diagnostics.Process.GetProcessesByName("ProcessName")
Since you've declared Process as a string parameter, Process.GetProcessesByName refers to the string instead of the System.Diagnostics method. Alternatively, you can use a different name for the string parameter.

How do I pass ItemSpec into GetBranchHistory()?

I'm trying to get information about specific branches in TFS, so to start, I'm trying to create a variable to assign as a BranchHistoryTreeItem. However, when I pass in the ItemSpec, I'm getting an error on Spec (not the definition, but where it's passed into GetBranchHistory):
Value of type 'Microsoft.TeamFoundation.VersionControl.Client.ItemSpec' cannot be converted to '1-dimensional array of Microsoft.TeamFoundation.VersionControl.Client.ItemSpec'
I understand the error, but I'm not entirely sure why it throwing it. Isn't this data type exactly what it's looking for? I believe I have the ItemSpec declared correctly, but I'm a bit lost here. Can anyone offer some advice on why I'm getting this? Code:
Sub GetBranchInfo()
Dim tfs As New TfsTeamProjectCollection(Common.BuildServerURI)
Dim Version = tfs.GetService(Of VersionControlServer)()
Dim Spec As New ItemSpec("$/Project1", RecursionType.None)
Dim BranchHistory As New BranchHistoryTreeItem(Version.GetBranchHistory(Spec, VersionSpec.Latest))
End Sub
GetBranchHistory takes an array of ItemSpecs.
My VB is a little rusty, but I think you want something like:
Dim Spec As New ItemSpec("$/Project1", RecursionType.None)
Dim Specs(1) = new ItemSpec() {Spec}
Dim BranchHistory As New BranchHistoryTreeItem(Version.GetBranchHistory(Specs, VersionSpec.Latest))

Constructing an object and calling a method without assignment in VB.Net

I'm not entirely sure what to call what C# does, so I haven't had any luck searching for the VB.Net equivalent syntax (if it exists, which I suspect it probably doesn't).
In c#, you can do this:
public void DoSomething() {
new MyHelper().DoIt(); // works just fine
}
But as far as I can tell, in VB.Net, you must assign the helper object to a local variable or you just get a syntax error:
Public Sub DoSomething()
New MyHelper().DoIt() ' won't compile
End Sub
Just one of those curiosity things I run into from day to day working on mixed language projects - often there is a VB.Net equivalent which uses less than obvious syntax. Anyone?
The magic word here is Call.
Public Sub DoSomething()
Call (New MyHelper()).DoIt()
Call New MyHelper().DoIt()
End Sub
Gideon Engelberth is right about using Call. It is the best option.
Another option is to use a With statement:
With New MyHelper()
.DoIt()
End With

VB.Net Running Threading with Reflected Objects

Running into problems creating objects through reflection and then running them on multiple threads.
I just cannot seem to figure out what I need to here:
For Each WorkerNode As XmlNode In oRunSettings.GetWorkerValues
Dim sWorkerName = WorkerNode.Attributes(SETTING_NAME_ID).Value
Dim oWorkerType As Type = Type.GetType(String.Format("Worker.{0}", sWorkerName))
Dim oWorker As Object = Activator.CreateInstance(oWorkerType)
Dim tWorker As Thread = New Thread(AddressOf oWorker.Process)
tWorker.Start()
Next
It is causing errors at the "AddressOf" because Object does not have a method called that. Do I need to do something with an interface?
First of all I want to say that I've never wrote code in VB so I can be completely wrong here but I'll try anyway.
It seems that you hold the created instance as Object instead of it's correct type.
Object does not contain method named Process, hence the error.
try casting the object to the correct type.
I hate when people answer their own question, but while waiting for an answer, I realized that I could just cast the object as its base object, and set the reflection from there. That is working now.