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.
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.
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
orDim 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;
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.
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.
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!