Even though it's inside of an if
block, the compiler doesn't know that T
is string
.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime
to string
)
You need to cast to object
, (which any T
can cast to), and from there to string
(since object
can be cast to string
).
For example:
T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;