简体   繁体   中英

nullable types in c#

I am a java beginner and I have to compare null values in java with null in C# .

I read that java does not assume anything to be null and always allocates memory but c# on the contrary assumes all to be null??? (did not understand what does this mean)

I also read that ordinary types in c# cannot be null but then i saw a code which says :

int? a = null;

int is ordinary type right?

I am really getting confused , can anybody help me out?

Thanks in advance

int is a primitive struct, yes. However,

int?

is syntactic sugar for

Nullable<int>

which is a completely different type.

See: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Take a look at this MSDN article :

Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value.

class NullableExample
{
    static void Main()
    {
        int? num = null;

        // Is the HasValue property true? 
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero 
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false 
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

null is pretty similar in C# and Java. C#'s struct s cannot be null, with the exception of Nullable<T> (which is itself a struct , but through some compiler magic can pretend to have a null value). Java's primitives cannot be null.

int? is shorthand for Nullable<int> . See Nullable Types for more info on that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM