K
Karl Meissner
I am having problem casting from object. I want to pass in an
value type as an object and then store it as a particular type.
The cast from object throws an exception if the types do not match.
class test {
short x;
// o can be any of the value types int, long, float
public void Set( object o ) {
x = ( short ) o; /// thows an exception if o is an int
}
public void Set2( object o ) {
int i = ( int ) o;
x = ( short ) i; /// works
}
}
....
test t = new test();
int j = 42;
t.Set2( j ); // good
t.Set( j ); // bad
Why wont the cast in Set work?
What good is object if I need to know what freaking type it is to use it?
Is there a stronger cast?
I suppose I could write a long if-else-if that test all the possible types
of the object o and cast it to the input o type and then cast that to
short but that is pretty lame.
Any ideas?
Also I am not allowed to use generics. Sigh....
Karl
value type as an object and then store it as a particular type.
The cast from object throws an exception if the types do not match.
class test {
short x;
// o can be any of the value types int, long, float
public void Set( object o ) {
x = ( short ) o; /// thows an exception if o is an int
}
public void Set2( object o ) {
int i = ( int ) o;
x = ( short ) i; /// works
}
}
....
test t = new test();
int j = 42;
t.Set2( j ); // good
t.Set( j ); // bad
Why wont the cast in Set work?
What good is object if I need to know what freaking type it is to use it?
Is there a stronger cast?
I suppose I could write a long if-else-if that test all the possible types
of the object o and cast it to the input o type and then cast that to
short but that is pretty lame.
Any ideas?
Also I am not allowed to use generics. Sigh....
Karl