0

I'm struggle with this little piece of code

static T Read<T>(object rawValue) 
{
    if (rawValue is int )
    {
        int n = 5 ; 
        return (T) n ; // Compilation error
    }

    return default(T) ;
}

while :

static T Read<T>(object rawValue) 
{
    if (rawValue is int )
    {
        int n = 5 ; 
        return (T) (object) n ; // Compile OK
    }

    return default(T) ;
}

Why do I need to pre cast it to object to make it compile?

Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
Pablo Honey
  • 1,074
  • 1
  • 10
  • 23
  • See [this](http://stackoverflow.com/questions/6407039/explicitly-cast-generic-type-parameters-to-any-interface) for the relevant part in the C# specification – Yuval Itzchakov Dec 21 '15 at 11:27
  • 2
    By the way, Eric Lippert [says](http://stackoverflow.com/a/8171547/447156): _Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong._ – Soner Gönül Dec 21 '15 at 11:30

0 Answers0