1

So if I want to pass a nullable value type such as a Int32? into a method, I must tell the method param that it is a nullable.

public void foo(Int32? arg){...}

If I pass a regular Int32 into arg it works. But if I change it to

public void foo(Int32 arg){...}

and pass in a nullable it freaks out.

So my question is does the ? change the type of Int32 ?

Is there an Int32? object or does the ? just set a flag in Int32 and make it nullable?

Basically I am asking what is happening under the hood.

Adel Khayata
  • 2,717
  • 10
  • 28
  • 46
DotNetRussell
  • 9,716
  • 10
  • 56
  • 111
  • `Int32?` is a shortcut for `Nullable`. I would assume `Nullable` is a wrapper class. – Khan Jul 30 '13 at 13:59
  • "Duplicate" : http://stackoverflow.com/questions/121680/whats-the-difference-between-int-and-int-in-c –  Jul 30 '13 at 14:03

3 Answers3

2

Int32? is the short form for Nullable<Int32>, so these are two different types. An Int32 can implicit casted to a Nullable<Int32>, but not the other way round.

In http://msdn.microsoft.com/de-de/library/b3h38hb0(v=vs.100).aspx you can see the two operators:

Explicit(Nullable<T> to T): Returns the value of a specified Nullable<T> value.
Implicit(T to Nullable<T>): Creates a new Nullable<T> object initialized to a specified value.
Roland Bär
  • 1,720
  • 3
  • 22
  • 33
  • Duplicate : http://stackoverflow.com/questions/4028830/c-sharp-nullableint-vs-int-is-there-any-difference –  Jul 30 '13 at 14:00
2

the Nullable struct implement implicit conversion of type int to int?, whereas the other way is explicit so in your first case the conversion is implicit and the second you must make an explicit cast. here is an extruct of the code from Nulable struct:

    public static implicit operator T?(T value)
{
   return new T?(value);
}
public static explicit operator T(T? value)
{
   return value.Value;
}
Swift
  • 1,861
  • 14
  • 17
0

Int32? is synonymous with Nullable<Int32> or just plain Nullable<int> or even int?

int? is a value type, and it can have the value null, which is why you can't pass it to a function argument of type int - what would happen if its value were null?

Jon G
  • 4,083
  • 22
  • 27