C# Null Conditional Operator with nullable datetime - c#

I am trying to learn use the null conditional operator but can't seem to get it to work,
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u].Value.ToShortDateString() ?? "Empty";
DateIn is a list of nullable DateTime (List<Datetime?>) .
I did debugging and all the values in DateIn[u] give null.
What am I doing wrong?

If all the values in the DateIn array are null, your code would throw a NullReferenceException.
You may use the null-propagation-operator here:
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u]?.ToShortDateString() ?? "Empty";
This operator (?.) now returns a nullable string. If DateIn[u] has a value, ToShortDateString() is called and the operator returns a nullable string with the returned value.
If DateIn[u] is null the operator returns null, too.

You have a mistake. First check for null values by HasValue and use single ? not double ?? like the following snippet:
string datetest = DOInfolist[i].RentalItem.SimCard.DateIn[u].HasValue ? DOInfolist[i].RentalItem.SimCard.DateIn[u].ToShortDateString() : "Empty";

Related

Converting null literal for Console.ReadLine() for string input

I am new to c# so i need some guidance with this.
string NumInput = Console.ReadLine();
in my code, this statement gives the warning of
converting null literal or possible null value to non-nullable type.
Is there any alternative to this code line or anything which can make this warning disapear
Firstly, you are seeing this message because you have the C# 8 Nullable reference type feature enabled in your project.
Console.ReadLine() returns a value that can be either a string or null but you are using it to set a variable of type string. Instead either use the var keyword which will implicitly set your variable to the same type as the return value or manually set your variable as type nullable string string?. the ? denotes a nullable reference type.
You may then want to check that your variable does infact hold a string before you use it:
string? NumInput = Console.ReadLine();
if (NumInput == null)
{
// ...
}

Write "?" in a string if a property is null

How can I write the Startedate like "?" is Startdate is null
public DateTime? StartDate { get; set; }
public override string ToString()
{
return String.Format("Course {0} ({1} is an {2} course, will be given by {3}, starts on {4}, costs {5:0.00} and will have maximum {6} participants"
, Name
, CourseId
, CourseType
, Teacher
, (StartDate == null ? "?" : StartDate)
, Price
, MaximumParticipants);
}
C# 6 lets you write this without ternary operator, like this:
StartDate?.ToString("dd-MM-yyyy") ?? "?"
?. will conditionally execute ToString only if StartDate is not null. Null coalesce operator ?? will complete the job by providing "?" string as a replacement for null value.
You can go further and replace String.Format with interpolating string, like this:
return $"Course {Name} ({CourseId} is an {CourseType} course, will be given by {Teacher}, starts on {StartDate?.ToString("dd-MM-yyyy") ?? "?"}, costs {Price:0.00} and will have maximum {MaximumParticipants} participants";
Both sides of the ternery operator need to be the same type. From the documentation:
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
So you can simply convert your date to a string (note the formatting is up to you):
(StartDate == null ? "?" : StartDate.Value.ToString("dd-MM-yyyy"))
You could tweak your existing code
(StartDate == null ? "?" : StartDate.ToString())
Or leverage Nullable<T> .HasValue
(StartDate.HasValue ? StartDate.ToString() : "?")
The point is, ?: requires the same type for both conditions.
you can use IsNullOrEmpty() function it will cover null or empty date
(IsNullOrEmpty(StartDate) ? "?" : StartDate.ToString("dd-MM-yyyy"))

converting string to datetime in C# on null value exception

I use the below code
extensionRequest[i].EndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString());
extensionRequest[i].ExtendedEndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ExtendedEndDate"].ToString());
extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString());
this works fine when values are coming from the DB
but when NULL values are returned it throws an exception!!
Should i check values for all three values like the code below
if (dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString()==null){
extensionRequest[i].ReceivedDate="";
}
else{
extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString());
}
or i should assign all dates to null on exception?!
is there any other way to do in single line? like tryparse or something?
I'll try being creative. You can create a Nullable TryParse as an Extension Method edition:
public static DateTime? TryParseNullable(this DateTime dateTime, string val)
{
DateTime outValue;
return DateTime.TryParse(val, out outValue) ? (DateTime?) outValue : null;
}
and then use:
extensionRequest[i].EndDate = DateTime.TryParseNullable(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString());
and that can be your one liner.
You can use DateTime.TryParse() method which returns true on successfull conversion otherwise returns false.
Note: calling ToString() on null throw NullReferenceException hence you need to check for null value before conversion.
Try This:
if(dsResult.Tables[0].Rows[i]["ActualEndDate"] != null)
DateTime.TryParse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString(),
out extensionRequest[i].EndDate);
You can check if value is null like this
extensionRequest[i].EndDate = Convert.IsDbNull(dsResult.Tables[0].Rows[i]["ActualEndDate"]) ? null : Convert.ToDateTime(dsResult.Tables[0].Rows[i]["ActualEndDate"]);
I'm sure .ToString() is not required.
It will be more readable if you cache a row to the local variable:
var row = dsResult.Tables[0].Rows[i];
...
extensionRequest[i].EndDate = Convert.IsDbNull(row["ActualEndDate"]) ? null : Convert.ToDateTime(row["ActualEndDate"]);
Be sure .EndDate and others allow null values. In other words, that is DateTime?

How do I convert a database number to hex when the field might be null?

I have trouble to convert from decimal to hex.
Here is my code:
select new
{
MessageID = table1.Field<Int32?>("MessageID"),
MessageIDHex = (String)table1.Field<Int32>("MessageID").ToString("X")
}
It gives me Error
with DBNUll.Value cant not change to System.In32
So I have tried
MessageIDHex= (String)table1.Field<Int32?>("MessageID").ToString("X")}
but it gives me another error.
How can I fix it or it does have another way to solve it.
Apparently, MessageID can be DBNull. The simplest solution is to read the value as a nullable int (to prevent the conversion error from occurring). If you use Field with a nullable type, DBNull is automatically converted to null, which can then be coerced to 0 with the ?? operator:
MessageIDHex = (table1.Field<Int32?>("MessageID") ?? 0).ToString("X")
Alternatively, if you prefer, you can have DBNull values in the database result in an empty or a null string for MessageIDHex:
MessageIDHex = table1.IsNull("MessageID") ? "" : table1.Field<Int32>("MessageID").ToString("X")
MessageIDHex = table1.IsNull("MessageID") ? null : table1.Field<Int32>("MessageID").ToString("X")

What's the differences between .ToString() and + ""

If I have a DateTime, and I do :
date.Year.ToString()
I get the Year as String. But Also if I do
date.Year + ""
the differences is only that the second one doesnt get an exception if there isn't the Date? (which i prefeer)
When you write date.Year + "" it will be compiled as a call to string.Concat(object, object):
String.Concat(date.Year, "")
Internally, the Concat method will call ToString on each (non-null) object.
Both approaches will throw a NullReferenceException if date is null. But you said date is of type DateTime. DateTime is a struct and so cannot be null.
If date is of type DateTime? and want to return an empty string if date is null then you can use this:
date.HasValue ? date.Value.Year.ToString() : ""
date.Year.ToString()
Won't work if date is null.
date.Year + ""
Works even if year is null as binary + operator substitutes null with a empty string.
This is what MSDN says about binary + operator concatenating two strings:
The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted.
More information on http://msdn.microsoft.com/en-us/library/aa691375%28VS.71%29.aspx
There is no difference if date.Year is not null.
In the second example the ToString() method is implicitly called on date.Year.

Categories