What is null in c#, java?

后端 未结 9 1191
挽巷
挽巷 2020-12-15 23:09

Like... is it 0 like in C++? Or is it some \"special\" object? Or maybe something totally different?

-- EDIT --

I do know what it is, the

9条回答
  •  粉色の甜心
    2020-12-15 23:44

    Since you're asking about implementation details, rather than semantics, the answer is specific to a given implementation.

    There are three things in C# that "null" can be. A reference, a pointer, and a nullable type.

    The implementation of C# on the CLR represents a null reference by zero bits. (Where the number of bits is the appropriate size to be a managed pointer on the particular version of the CLR that you're running.)

    Unsurprisingly, a null pointer is represented the same way. You can demonstrate this in C# by making an unsafe block, making a null pointer to void, and then converting that to IntPtr, and then converting the IntPtr to int (or long, on 64 bit systems). Sure enough, you'll get zero.

    A null nullable value type is also implemented by zeroes, though in a different way. When you say

    int? j = null;

    what we actually create is the moral equivalent of:

    struct NullableInt 
    {
        int value;
        bool hasValue;
    }
    

    With appropriate accessor methods, and so on. When one of those things is assigned null, we just fill the whole thing with zero bits. The value is the integer zero, and the hasValue is filled with zeroes and therefore becomes false; a nullable type with the hasValue field set to false is considered to be null.

    I do not know what the implementation details are on other implementations of C# / the CLI. I would be surprised if they were different; this is the obvious and sensible way to implement nulls. But if you have questions about a specific implementation detail, you'll have to ask someone who knows about the implementation you're interested in.

提交回复
热议问题