Interviews3 answers
nullable types example
3 Answers
Nullable types is essential as value type doesn't hold a null value
Declaring Nullable Type
1. Append a question mark, ?, to the type name
DateTime? startDate;
2. Either you can assign a normal value or may assign a null value to it;
strDate = null;
OR
strDate = DateTime.Now;
Working with Nullable Types
bool isNull = strDate == null;
Console.WriteLine("isNull: " + isNull);
The above example shows that you only need to use the equals operator to check for null. You could also make the equality check as part of an if statement, like this:
int products;
if (unitsInStock == null)
{
products = 0;
}
else
{
products = (int)unitsInStock;
}
Note: Notice the cast operator in the else clause above. An explicit conversion is required when assigning from nullable to non-nullable types.
Fortunately, there's a better way to perform the same task, using the coalesce operator, ??, shown below:
int availableUnits = unitsInStock ?? 0;
The coalesce operator works like this: if the first value (left hand side) is null, then C# evaluates the second expression (right hand side).
Raghav MehraPosted Aug 25, 2014, 11:14 PM EDT
Nullable types can store null values to the data Type.
For example ,
int age;
In a form if the user skips the Age to enter, then the value of age is stored as Zero
In this case if we declare as int? age; instead of int age; then the value of age will be null and not zero,
which is meaningful.
RamaPosted Aug 14, 2014, 11:57 PM EDT
Int? someID = null;
If(someID.HasVAlue)
{
}
Guest UserPosted Aug 1, 2014, 6:59 PM EDT
