Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting generics parameters [duplicate]

Tags:

c#

generics

Can you explain why first line of code it give me compiler error and next one not.

public void DoStuff<T>(T obj)
{
 Int32 x = (Int32) obj; // 1. Error
 Int32 y=(Int32)(Object)obj; //2. Works fine
}

1 Answers

In order to cast, you need to know at compile-time how to cast from one type to another. For example:

long l = 34;
int i = (int)l;

This works because the compiler knows how to cast a long to an int. It also knows how to convert object to int:

object o = 42;
int i = (int)o;

However, not all types can be cast to int:

string s = "48";
int i = (int)s; // This will not compile.

Since your generic can represent any type, you can't just cast to an int all willy-nilly for any type. You have to first cast it to something that can be cast to int. Since anything can be cast to object, and object and be cast to anything, your double-cast will work.

like image 142
Joe Enos Avatar answered Sep 17 '26 02:09

Joe Enos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!