开发者

Do C# Nullable variables still function as value types?

If I declare a nullable (either via Nulla开发者_StackOverflow中文版ble or the ? symbol) variable from a value type, does it still respect the rules of value types (i.e. pass by value by default, deallocated when it falls out of scope, not when the garbage collector runs) or does it turn into a reference type since it's actually of type Nullable?


The documentation is here:

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

As you can see, the documentation describes this as the "nullable structure", indicating that it is a value type. Also, the documentation gives the first lines of the declaration of the type:

public struct Nullable<T> where T : struct, new()

again showing that the type is a value type.


Yes, System.Nullable is a generic Struct, ie value type.


Nullable value types are essentially just a struct wrapper around a value type which allows them to be flagged as null.

something like this:

struct Nullable<T>
{
    public T Value;
    public bool HasValue;
}

I believe it's actually more complex than that under the hood, and the compiler does lots of nice stuff for you so you can write for example if(myInt == null). But yes, they are still value types.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜