Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by 'ref' - c#

Tags:

c#

ref

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
    }
}
  1. Can anyone explain this? Im guessing it has something to do with ref's being very strict with derived classes.

  2. Is there any way I can pass an object of type string to foo(ref object varname)?

like image 639
maxp Avatar asked Dec 12 '22 12:12

maxp


1 Answers

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.

like image 170
Marc Gravell Avatar answered Dec 30 '22 17:12

Marc Gravell