Hello,
Try the following done in this case with .NET 5, C#9
Helper class
public static class DateHelpers
{
public static bool RouteCheck(ref DateTime? travelTime) => travelTime.HasValue;
public static DateTime? TryParse(string text) => DateTime.TryParse(text, out var date) ? date : (DateTime?)null;
}
Program.cs
class Program
{
static void Main(string[] args)
{
Nullable<DateTime> TravelTime = null;
Console.WriteLine(DateHelpers.RouteCheck(ref TravelTime));
TravelTime = DateTime.Now;
Console.WriteLine(DateHelpers.RouteCheck(ref TravelTime));
string someDate = "01/01/2021 09:00:00";
var test = DateHelpers.TryParse(someDate);
if (test.HasValue)
{
Console.WriteLine(DateHelpers.RouteCheck(ref TravelTime));
}
else
{
Console.WriteLine("Not a date time");
}
someDate = "";
test = DateHelpers.TryParse(someDate);
if (test.HasValue)
{
Console.WriteLine(DateHelpers.RouteCheck(ref TravelTime));
}
else
{
Console.WriteLine("Not a date time");
}
Console.ReadLine();
}
}
Edit
In regards to checking the type if there are other types e.g. int use int.TryParse or perhaps a generic check where T is the type.
using System;
namespace YourNamespace
{
public static class DateHelpers
{
public static bool RouteCheck(ref DateTime? travelTime) => travelTime.HasValue;
public static DateTime? TryParse(string text) => DateTime.TryParse(text, out var value) ? value : (DateTime?)null;
public static bool Is<T>(this string value)
{
if (string.IsNullOrEmpty(value)) return false;
var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
if (!conv.CanConvertFrom(typeof(string))) return false;
try
{
conv.ConvertFrom(value);
return true;
}
catch
{
// ignored
}
return false;
}
}
}