I have the following (simplified) method:
private static string GetStringFromValue<T>(T val)
{
if (typeof(T) == typeof(DateTime))
{
return string.Format("{0}", ((DateTime)val).Year.ToString("0000"));
}
return string.Empty;
}
At the cast "(DateTime)val" I get the following error:
Cannot cast expression of Type 'T' to type 'DateTime'
What can I do to access the Year property of the DateTime parameter?
UPDATE: Thank you for all your very fast answers. This method (and method name) is really (!) simplified to show exactly my problem and to let everyone just copy&paste it into his own visual studio. It is just that I wanted to add some Type specific values if the type is a DateTime. Beside that 99% of the method is the same.
Change it to
return string.Format("{0:yyyy}", val);
To answer the question, the compiler does not realize that T
is DateTime
.
To perform this cast, you need to cast through object
, like this:
return ((DateTime)(object)val).Year.ToString("0000");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With