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 TargetInvocationExceptions 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?
.ToString()Which could result in a "null value" error being thrown, alternativly give us the erorr your getting "falls on it's head" isn't as informative as "system.whatever returned a value of X when it expected Y"InnerException?TargetInvocationExceptionwith the message "A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll". Visual Studio displays the Source Not Available page and there are no stack traces available either.await task;should fail, even if the result value is null. TheDoSomething()method always returns a non-null object, sotaskitself is always non-null, and soawait taskshould always be valid. The result is null, but you never bother to use it in that third example, so it being null is not a problem. Other than that, the answer from un-lucky addresses your concerns: there's not a problem withNothingvsnull...you wouldn't be allowed to dereferenceNothingin VB either!.ToString()method orawait()is not capable of handling null that's the reason for the exception you are getting.