According to the MSDN entry for Nothing (Visual Basic)
Nothing represents the default value of a data type.
It has also been noted by some that "...the Nothing
keyword is actually equivalent to C#’s default(T)
keyword".
This has been giving me some anomalous behaviour in a multi-language solution I have been working on recently. Specifically I have been getting with more than a few TargetInvocationException
s being thrown at the C# end when the VB.NET async methods return Nothing
.
Is it possible to set a variable in the VB.NET projects to C#'s null
and be able to test for this null
value in both C# and VB.NET.
Here is a snippet that is not behaving as expected. The C# project imports the VB.NET project as a reference.
VB.NET Side
Public Function DoSomething() As Task(Of Object)
Dim tcs = New TaskCompletionSource(Of Object)
Dim params = Tuple.Create("parameters", tcs)
AnotherMethod(params)
Return tcs.Task
End Function
Public Sub AnotherMethod(params As Tuple(Of String, TaskCompletionSource(Of Object))
' do some activities
If result = "Success" Then
params.Item2.SetResult("we were successful") ' result can also be of different type
Else
params.Item2.SetResult(Nothing) ' could this be the source of the exception?
End If
End Sub
C# Side
public async void AwaitSomething1()
{
var result = "";
result = (await DoSomething()).ToString(); // fails if Result is Nothing
}
public async void AwaitSomething2()
{
var result = "";
result = (string)(await DoSomething()); // fails if Result is Nothing
}
public async void AwaitSomething3()
{
var task = DoSomething();
await task; // also fails if Result is Nothing
}
There is no exception thrown when VB.NET's AnotherMethod
is successful. However, when it is not successful and tcs
's result is set to Nothing
, everything falls on its head.
How can I effectively SetResult
to Nothing
without resulting in an exception or, otherwise, how can I SetResult
to C#'s null
?