Reputation: 3476
I am casting dynamically with generics and have come across a problem when casting from long
to int
. The problem basically boils down to the following:
While this works:
long l = 10;
int i = (int) l;
This does not:
long l = 10;
object o = l;
int i = (int)o;
So the problem is that I have an object as variable of type object
but the instance behind is of type long
and I want to cast this to an int
. What I have found so far is this article: Representation and identity (Eric Lippert).
So what would be valid is this:
long l = 10;
object o = l;
int i = (int)(long)o;
What I have tried is this:
long l = 10;
object o = l;
int i = (int) Convert.ChangeType(o, typeof(long));
But this does not work. Now the question is how can I cast dynamically without System.InvalidCastException
?
Currently I have is this (and it does NOT work):
public T Parse<T>(object value){
return (T) Convert.ChangeType(value, value.GetType());
}
How can I make it work and be able to pass an object of type long
with T beeing int
.
Upvotes: 4
Views: 972
Reputation: 62492
Instead of this:
long l = 10;
object o = l;
int i = (int) Convert.ChangeType(o, typeof(long));
Just ask Convert
to give you an int
, as that's what you want:
long l = 10;
object o = l;
int i = (int) Convert.ChangeType(o, typeof(int));
The Convert
class with use the IConvertable
interface to do the conversion for you.
Using this approach you can write your Parse
function like this:
T Parse<T>(object value)
{
return (T) Convert.ChangeType(value, typeof(T));
}
And call it like this:
long l = 10;
object o = l;
int i=Parse<int>(o);
Upvotes: 2
Reputation: 993
How about this
return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value.ToString());
It will still fail if your long value is too big for an int so you would still need to deal with that.
Look at this Generic TryParse
Upvotes: 0
Reputation: 20585
long
to int
is type casting, when you doing this you are just changing value of one type to another similar type, in some case that may lead to value loss, and compiler knows how to perform so.
object
to int
is type conversion. you are attempting to change the underlying type. Hence the runtime
error.
Have a look at Casting and Type Conversion & Boxing & Unboxing
Upvotes: 0