开发者

Can structs really not be null in C#?

Below is some code that demonstrates I cannot declare and initialize a struct type as null. The Nullable type is a struct, so why am I able to set it to null?

Nullable<bool> b = null;
if (b.HasValue)
{
    Console.WriteLine("HasValue == true");
}

//Does not compile...
Foo f = null;
if (f.HasValue)
{
    Console.WriteLine("HasValue == true");
}

Where Foo is defined as

public struct Foo
{
    private bool _hasValue;
    private string _value;

    public Foo(string value)
    {
        _hasValue = true;
        _value = value;
    }

    public bool HasValue
    {
        get { return _hasValue; }
    }

    public string Value
    {
        get { return _value; }
    }
}

The question has been answered (see below). To clarify I'll post an example. The C# code:

using System;

class Program
{
    static void Main(string[] args)
    {
        Nullable<bool> a;
        Nullable<bool> b = null;
    }
}

produces the following IL:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] valuetype [mscorlib]System.Nullable`1<bool> a,
           [1] valuetype [mscorlib]System.Nullabl开发者_JAVA百科e`1<bool> b)
  IL_0000:  nop
  IL_0001:  ldloca.s   b
  IL_0003:  initobj    valuetype [mscorlib]System.Nullable`1<bool>
  IL_0009:  ret
} // end of method Program::Main

a and b are declared, but only b is initialized.


The C# compiler provides you with a bit of sugar so you really are doing this:

Nullable<bool> b = new Nullable<bool>();

Here is the syntactic sugar

bool? b = null;    
if (b ?? false) 
{
   b = true;
}


C# has some syntax sugar that allows you to appear to set a nullable type to null. What you are actually doing under the covers is setting the nullable type's HasValue property to false.


Because you're not actually setting the Nullable<T> variable to null. The struct is still there. It represents null via an internal bit flag in the struct.

There's also some compiler sugar to make magic happen behind the scenes.


You can't set a structure to null, but you can have implicit type conversions, which is what is happening under the hood.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜