casting from object


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....






Chris Hornberger

If I had to guess, I'd say it's because of some pre-cast bounds or
address or address-size checking or something along those lines.

Personally I'd use a cascading thing like you're doing in Set2 anyway,
start with a double -> int -> short, as an example.

At least that way, you're always guaranteed to get a return value, if
not boxed up in the type you're expecting, or you'd be able to stack
trace the failures and log your problems.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question