Much to my dismay, the follow code wont compile.
It will however compile if I remove the ref
keyword.
class xyz
{
static void foo(ref object aaa)
{
}
static void bar()
{
string bbb="";
foo(ref bbb);
//foo(ref (object)bbb); also doesnt work
}
}
Can anyone explain this? Im guessing it has something to do with ref's being very strict with derived classes.
Is there any way I can pass an
object of type string to foo(ref
object varname)
?
It has to be an exact match, else foo
could do:
aaa = 123;
which would be valid for foo
(it will box the int
to an object
), but not for bar
(where it is a string
).
Two immediate options; firstly, use an intermediate variable and a type-check:
object tmp = bbb;
foo(ref tmp);
bbb = (string)tmp;
or alternatively, maybe try generics (foo<T>(ref T aaa)
); or treat bbb
as object
instead of string
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With