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 tofoo(ref?
object varname)
It has to be an exact match, else
foocould do:which would be valid for
foo(it will box theintto anobject), but not forbar(where it is astring).Two immediate options; firstly, use an intermediate variable and a type-check:
or alternatively, maybe try generics (
foo<T>(ref T aaa)); or treatbbbasobjectinstead ofstring.