Hi,
It is not easier to just return it?
public object foo( object o )
Anyway, your code has several things (complex and basics) involved that I
will try to explain.
Boxing and unboxing
--------------------------
when you convert a value type to a reference type ie : int to object you
create a new instance of object in the heap. this is better explained with
an example
double d = 0.0;
object o = d;
d=4;
now you have TWO double one in the heap referenced by "o" and another in the
stack "d" , therefore
d == (double)o is FALSE
now when you say foo(ref (object)i) you are CREATING a new object in the
heap (boxing) the int.
what happen is that with a ref parameter you cannot do this, a ref parameter
NEEDS to be a lvalue, meaning that it should be a expression valid in the
left part of an assignation like:
(object)i=4;
which is not valid ( you are getting the same problem in the if/else
construct you are using.
this is needed cause otherwise the reference used is lost at return , think
about it, you are creating a new instance and you are NOT keeping any
reference to it. !!!
I think that you will get several answer to this, probably one with a
better written techical english than me :)
Cheers,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Jazper Manto" <ej*****@hotmail.com> wrote in message
news:um**************@TK2MSFTNGP09.phx.gbl...
hi
i want to have a method with a ref object parameter so that i can pass any
object by reference and write output in it like code below. the problem is
it does not work in c# like i coded it. i do NOT want to use overloads!!!
is it possible? if yes, how?
thanx jazper
--- CODE ---
public void foo(ref object o)
{
if( o is int) ((int)o) = 1;
else if( o is double) ((double)o) = 3.5;
else if( o is string) ((string)o) = "test";
else throw new Exception("type not recognized!");
}
public void callfoo()
{
int i = 0;
double d = 0.0;
string s = string.Empty;
foo(ref (object)i);
foo(ref (object)d);
foo(ref (object)s);
}