Why can you assign Nothing to an Integer in VB.NET?

后端 未结 5 1024
星月不相逢
星月不相逢 2021-01-17 07:22

Why am I allowed to assign Nothing to a value-type in VB.NET:

Dim x as Integer = Nothing

But I\'m not allowed to assign

5条回答
  •  半阙折子戏
    2021-01-17 07:48

    The equivalent C# code looks like this:

    int x;
    x = default(int);
    

    Note that for reference types, the same still holds:

    Dim y As Object
    y = Nothing
    

    That VB.Net code would look like this if mapped directly to C#:

    object y;
    y = default(object);
    

    It's just a nice thing that the default for object (or any other reference type) in .Net is null. So we see that VB.Net's Nothing is not a direct analog to C#'s null, at least when used with value types.

提交回复
热议问题