0

Can anyone help me in understanding to know the difference between decimal and decimal? or int and int??.

When should I use them and what are the positives of using either of them.

Richard Ev
  • 52,939
  • 59
  • 191
  • 278
Findings
  • 103
  • 4
  • 12
  • Take a look at this [Microsoft page](http://msdn.microsoft.com/it-it/library/2cf62fcy.aspx) – Marco Apr 12 '12 at 17:14
  • possible duplicate of [What does "DateTime?" mean in C#?](http://stackoverflow.com/questions/109859/what-does-datetime-mean-in-c) – phoog Apr 12 '12 at 17:41

4 Answers4

14

data types with ? are nullable types. They can hold null value as well
Check out this Source link

  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a
    reference type. (Reference types already support the null value.)
  • The syntax T? (in C#) is shorthand for System.Nullable, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type in the same way as for an ordinary value type, for example: C#: int? x = 10; or double? d = 4.108;

    VB.NET: Dim x As Nullable(Of Integer) = 10 or Dim d As Nullable(Of Double) = 4.108

  • Use the System.Nullable.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example

    C#: int j = x.GetValueOrDefault();

    VB.NET: Dim j as Integer = x.GetValueOrDefault()

  • Use the HasValue and Value read-only properties to test for null and retrieve the value.

  • The HasValue property returns true if the variable contains a value, or false if it is null.
  • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
  • The default value for a nullable type variable sets HasValue to false. The Value is undefined.
    In C# 4.0
  • Use the ?? (C#) operator to assign a default value that will be applied when a nullable type whose current value is null is assigned
    to a non-nullable type, for example
int? x = null; 
int y = x ?? -1;
Habib
  • 219,104
  • 29
  • 407
  • 436
6

The ? after the type is describing that it is nullable. int? and decimal? are short-hand for Nullable<int> and Nullable<decimal>.

This allows the variable to hold its type or a null value.

Khan
  • 17,904
  • 5
  • 47
  • 59
1

The ? form just means it's a nullable value type. It's a shortcut for Nullable<decimal> or Nullable<int>. A good time to use it would be when you want to be able to indicate that there is no value assigned to that variable.

itsme86
  • 19,266
  • 4
  • 41
  • 57
0

One use-case is if you have things like a DateTime and you want to indicate that you haven't assigned a value to it yet. Rather than set it to a "Magic date" like 01/01/1970, you can set it to null. Much more straightforward!

Mr Lister
  • 45,515
  • 15
  • 108
  • 150