In C#, I have some code that looks like:
(await GetBoolAsync()).ShouldBeTrue();
ShouldBeTrue() is an extension method from the Shouldly library that operates on Booleans.
VB.NET doesn't seem to like wrapping the Await keyword in parenthesis:
(Await GetBoolAsync()).ShouldBeTrue()
The compiler reports a syntax error on the opening parenthesis at the beginning of the line. I can work around it by declaring an intermediate variable, but is there a way to achieve this in one line like C#?
A full console application to reproduce this:
Imports System.Runtime.CompilerServices
Module Module1
Sub Main
End Sub
Async Function Test() As Task
(Await GetBoolAsync()).ShouldBeTrue()
End Function
Function GetBoolAsync() As Task(Of Boolean)
Return Task.FromResult(True)
End Function
<Extension()>
Public Sub ShouldBeTrue(x As Boolean)
End Sub
End Module
The error is very unhelpful:
error BC30035: Syntax error.
There is a special syntax for doing so - you should use the Call keyword:
Async Function Test() As Task
Call (Await GetBoolAsync()).ShouldBeTrue()
End Function
That's because you cannot directly call a member of non-literal expression in Visual Basic, like you would in C#:
(5).ToString() 'It is wrong!
And in this particular case this includes the result of Await.
Hope that helps!
Related
Basically, it asks for a sub with Task as a parameter. That's what Action(of Task) right?
Why?
I know I can pass normal sub to continueWith. I never remember passing a sub that requires a task parameter.
It is by the definition. 'ContinueWith' should in most cases operate with the result of 'antecedent' task. If you forget how to call 'ContinueWith', Visual Studio 'Peek Definition' will help you. So, right clicking on 'ContinueWith' and by choosing 'Peek Definition' you will examine the signature. Basically, it looks like is shown in the snippet below.
public Task<TNewResult> ContinueWith<TNewResult>(
Func<Task<TResult>, TNewResult> continuationFunction)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return this.ContinueWith<TNewResult>(continuationFunction, TaskScheduler.Current, new CancellationToken(), TaskContinuationOptions.None, ref stackMark);
}
If it is too complicated, you can use a snippet and save an example and then inserted when you need it.
So, let's create an example.
Module Module1
Sub Main()
Dim taskA As Task(Of DayOfWeek) = Task.Run(Function() DateTime.Today.DayOfWeek )
' Execute the continuation when the antecedent finishes.
Dim taskB As Task(Of string) = taskA.ContinueWith(Function (antecedent)
Return $"Today is {antecedent.Result}"
End Function)
taskb.Wait()
Console.WriteLine(taskB.Result)
Console.ReadLine()
End Sub
End Module
I know that a function of a Module can be called in a formula like this:
=GetMyModuleFunction()
Now I would like to call a Class Module function. I don't know if a Class Module can be instantiated in a formula at all so I've created a function in a Module so I can call it just like =GetMyModuleFunction():
' Class Module MyClassModule:
Public Property Get MyProperty() As String
MyProperty = "Hello World!"
End Property
Public Function GetMyFunction() As String
GetMyFunction = "Hello World!"
End Function
' End Class Module MyClassModule
' Module MyModule:
Public Function GetMyClassModule() As MyClassModule
Set GetMyClassModule = New MyClassModule
End Function
' End Module MyModule
So after that I tried in the formula bar:
=GetMyClassModule().GetMyFunction()
=GetMyClassModule().MyProperty
Which shows an error dialog that the formula is invalid. Is it not possible what I'm trying to achieve here? Currently I use Modules instead but functions and subs with duplicate names are confusing and error prone to use in Modules..
Your question is similar to the question asked here: Call VBA function that returns custom type from spreadsheet
You can only return data types that Excel understands from a user-defined function. Excel does not understand custom data types.
But you can wrap your class properties or functions with a regular module function (UDF) like so:
Public Function GetMyClassModuleFunction() As String
GetMyClassModuleFunction = GetMyClassModule.GetMyFunction()
End Function
I've recently entered the joyful world of VB.NET, for the life of me however, I can't seem to figure out why the following is not working.
When I write this code here, all is well:
MyNavigationCommand = New RelayCommand(AddressOf Navigate)
Private Sub Navigate()
Navigator.NavigateTo(NavigationRoutes.DetailScreen)
End Sub
However, when I try to do exactly the same using the lambda syntax, my code inside the lambda doesn't get hit when I click the button that triggers the command.
The following line, doesn't work:
MyNavigationCommand = New RelayCommand(Sub() Navigator.NavigateTo(NavigationRoutes.DetailScreen))
This should work exactly the same as my previous approach, shouldn't it? Or am I missing something?
I'm not sure what's going wrong for you. This is my code that I wrote to test this:
Sub Main
Dim MyNavigationCommand = New RelayCommand(AddressOf Navigate)
Dim MyNavigationCommand2 = New RelayCommand(Sub() Console.WriteLine("!"))
Navigate
MyNavigationCommand
MyNavigationCommand2
End Sub
Public Delegate Sub RelayCommand
Public Sub Navigate()
Console.WriteLine("!")
End Sub
When run this code produces three lines of !.
It is easy to call a function inside a classModule using CallByName
How about functions inside standard module?
''#inside class module
''#classModule name: clsExample
Function classFunc1()
MsgBox "I'm class module 1"
End Function
''#
''#inside standard module
''#Module name: module1
Function Func1()
MsgBox "I'm standard module 1"
End Function
''#
''# The main sub
Sub Main()
''# to call function inside class module
dim clsObj as New clsExample
Call CallByName(clsObj,"ClassFunc1")
''# here's the question... how to call a function inside a standard module
''# how to declare the object "stdObj" in reference to module1?
Call CallByName(stdObj,"Func1") ''# is this correct?
End Sub
I think jtolle's response addressed the question best - the small reference to Application.Run may be the answer. The questioner doesn't want to use simply func1 or Module1.func1 - the reason one would want to use CallByName in the first place is that the desired function.sub name is not known at compile time. In this case, Application.Run does work, e.g.:
Dim ModuleName As String
Dim FuncName As String
Module1Name = "Module1"
FuncName = "func1"
Application.Run ModuleName & "." & FuncName
You can also prepend the Project Name before the ModuleName and add another period ".".
Unfortunately, Application.Run does not return any values, so while you can call a function, you won't get its return value.
Although it is an old question and OP asked for CallByName in a standard module, the correct pieces of advice are scattered through answers and comments, and some may not be that accurate, at least in 2020.
As SlowLearner stated, Application.run DOES return a Variant, and in that way both branchs below are equivalent, except by handling errors, as commented around Horowitz's answer:
Dim LoadEnumAndDataFrom as Variant
'FunctionName returns a Variant Array
if fCallByName then
LoadEnumAndDataFrom = CallByName(ClassObj, "FunctionNameAtClass", VbMethod)
else
'After moving back function for a standard module
LoadEnumAndDataFrom = Application.Run("StandardModuleName" & "." & "FunctionNameAtStandard")
endif
I actually just did this above and had no errors at all, tested in Word, Excel and Access, and all return the same Array.
Unfortunately, there is an exception: Outlook's object Model is too protected and it does not have the Run method.
CallByName works only with class objects.
If your subroutine is in a standard module, you can do this:
Sub Main()
Module1.Func1
End Sub
If it's a function, then you'll probably want to capture the return value; something like this:
Sub Main()
Dim var
var = Module1.Func1
End Sub
Modules in VB6 and VBA are something like static classes, but unfortunately VB doesn't accept Module1 as an object. You can write Module1.Func1 like C.Func1 (C being an instance of some Class1), but this is obviously done by the Compiler, not at runtime.
Idea: Convert the Module1 to a class, Create a "Public Module1 as Module1" in your Startup-module and "Set Module1 = New Module1" in your "Sub Main".
Unfortunately it is not possible to prepend the ProjectName before the ModuleName and add another period "." In MS Word this throws a runtime error 438. The call is restricted to the use of simply ModuleName.ProcName.
There's some code in our project that looks a bit like this:
Private Sub Method1()
Call InnerMethod
End Sub
Private Sub Method2()
InnerMethod
End Sub
Private Sub InnerMethod()
'' stuff
End Sub
What's the advantage of doing Method1 over Method2?
From the MSDN:
You are not required to use the Call
keyword when calling a procedure.
However, if you use the Call keyword
to call a procedure that requires
arguments, argumentlist must be
enclosed in parentheses. If you omit
the Call keyword, you also must omit
the parentheses around argumentlist.
If you use either Call syntax to call
any intrinsic or user-defined
function, the function's return value
is discarded.
For example:
Sub Proc1()
Debug.Print "Hello World"
End Sub
Sub Proc2(text As String)
Debug.Print "Hello " & text
End Sub
In the immediate window, if you enter
Proc1
then "Hello World" prints. If you enter
Call Proc1
then "Hello World" prints. If you enter
Proc2 "World"
then "Hello World" prints. If you enter
Call Proc2 "World"
you get a compile error. You would have to enter
Call Proc2("World")
Call does nothing special other than call the method. It is a hang over from the old days of Basic when all lines had to start with a keyword. "Let" is another of these keywords, which was always put before an assignment, but is no longer required.
Method1 and Method2 do the exact same thing.
I have found a major difference about 'call' keyword with functions that having, ByRef Arguments (I have found this in MS-Access VBA editor). If you are calling the function without 'Call' keyword, ByRef aruments will not set for the calle. For Ex:
Private Function Test(Optional ByRef refArg As String) As Boolean
refArg = "Test"
Test = True
End Function
If you call the function without the Call keyword like
Dim a As String
Test(a)
a will be an empty string, after the call returns
If you call the function with the Call keyword like
Dim a As String
Call Test(a)
a will contain the string Test
The detailed explanation provided in the following link:
Cannot use parentheses when calling a Sub
There's no difference.
Here's a post which describes when you need to use call vs not using it and when to parentheses around your parameters.
You can also read more about call from MSDN. Essentially the main difference is that when you use call to call a function you can't access the return value.