0

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

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
user1079065
  • 2,085
  • 9
  • 30
  • 53

3 Answers3

3

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

dodexahedron
  • 4,584
  • 1
  • 25
  • 37
  • Hey.. thanks a lot... does that mean they are similar to generics in java? – user1079065 Feb 04 '14 at 15:55
  • 1
    The System.Nullable class is a generic type, meaning it can hold various other types, but the concept of generics is not equivalent to the concept of the System.Nullable class itself, no. – dodexahedron Feb 04 '14 at 15:58
1

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);
        }
    }
}
jnovo
  • 5,659
  • 2
  • 38
  • 56
0

null is pretty similar in C# and Java. C#'s structs 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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122