CSharp - Generic Type Parameters Conversions

Introduction

Suppose you have the following generic method.

DateTime Test<T> (T arg)
{
}

In the method you would convert arg which is a generic type parameter to DateTime

You can use the as operator:

DateTime Test<T> (T arg)
{
     DateTime sb = arg as DateTime;
     if (sb != null) 
          return sb;
}

A more general solution is to first cast to object.

return (DateTime) (object) arg;

Unboxing

Suppose you have a generic to convert generic type parameter to an int

int Test<T> (T arg){
}

You can do the same trick:first cast to object and then to int:

int Test<T> (T x) {
   return (int) (object) x;
}