RyanG
RyanG

Reputation: 7213

Do C# Nullable variables still function as value types?

If I declare a nullable (either via Nullable 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?

Upvotes: 2

Views: 330

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660455

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.

Upvotes: 7

fearofawhackplanet
fearofawhackplanet

Reputation: 53446

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.

Upvotes: 1

Paul Creasey
Paul Creasey

Reputation: 28874

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

Upvotes: 3

Related Questions