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
.