The reason you're getting an error is because tTime.ToString("hh:mm tt")
tries to forcibly convert its value to a string, with the required format.
If that value is null, there is no way for the conversion to handle it, thus throwing an error.
One way to do it is by following @KevinCloet's answer, where he simply checks if the tTime
has a value, and converts it if it does.
// validation ? if true : if false
Console.WriteLine(tTime.HasValue ? tTime.Value.ToString("hh:mm tt") : String.Empty);
which could also be written as:
// Boolean values don't need = true
if(tTime.HasValue){
Console.WriteLine(tTime.Value.ToString("hh:mm tt"));
}else{
Console.WriteLine(String.Empty);
}
Another way to do it is through a try{}catch(){}
method, which is almost the same as the extended if
statement
try{
Console.WriteLine(tTime.Value.ToString("hh:mm tt"));
}
catch(Exception e){
// You don't actually need the 'Exception e',
// however 'e.Message' will tell you exactly what went wrong
Console.WriteLine(String.Empty);
}
I hope this explanation will help you understand, rather than just give you an answer.
Edit:
Based on Jon Skeets answer on "" vs String.Empty, you can essentially use either.