2

I have a VB class library with a test method. Which will return an Integer (sometimes Nothing will be returned).

Public Class Class1
    Public Function testMethod() As Integer
        'Some code here
        Return Nothing
    End Function
End Class 

If I call the method in a VB Project, everything works great as expected. For example:

  Dim output As String = testMethod().ToString() ' Works fine and output =""

But when I call the method by creating an object in C# application, it will throw error as null when the return value is Nothing.

VBTestLib.Class1 classObject = new VBTestLib.Class1();
string objectStringValue = classObject.testMethod().ToString(); // Error

Which means Nothing will be converted to null (null.ToString() is not allowed). Now consider the next example:

 int objectIntValue = classObject.testMethod(); // objectIntValue = 0

Here Nothing will be converted to the default value of the int (0). I have extended the testing using dynamic then also the assigned value is 0. i.e.,

 dynamic objectDynamicValue = classObject.testMethod();// objectDynamicValue = 0

So my question is, what is Nothing? How it will be converted when assigned to a C# type? Or shall I conclude that:

If a VB Method returns Nothing and the value is assigned to a C# variable of value type then the default value of method's return type will be assigned. And if it is assigned to a reference type variable then null will be assigned.

theB
  • 6,450
  • 1
  • 28
  • 38
Suji
  • 1,326
  • 1
  • 12
  • 27

1 Answers1

2

As I mentioned in the question (I assumed as well), Nothing Represents the default value of any data type (C# default(T)). For reference types, the default value is the null reference. For value types, the default value depends on whether the value type is nullable.

Here in my VB code the return value of the method is Integer (value type) So nothing will be its default value 0. That is why 0 is assigned to the dynamic type also. But it is not an alternative for null or it is not equivalent of null.

theB
  • 6,450
  • 1
  • 28
  • 38
Suji
  • 1,326
  • 1
  • 12
  • 27