Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast T parameter in generic method to DateTime

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.

like image 307
Chris Avatar asked Aug 24 '10 16:08

Chris


1 Answers

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");
like image 62
SLaks Avatar answered Oct 11 '22 18:10

SLaks