Objects, parameters, and the ref keyword in C #

When the formal argument of a method is of type "object", through inheritance it is possible that the actual argument is any type of object. Once in a method an object can be added to the expected type. Everything is fine.

If, however, the method signature has a formal argument "object" using the keyword ref ie methodname (ref object), the compiler generates an error message:

"The best overloaded method match for" ByRefTest.Program.changeMeByRef (ref object) "contains some invalid arguments." Argument "1": cannot be converted from "ref ByRefTest.Person" to "ref object" "

The difference between using or not using a reflex when passing objects as parameters is very well explained in A. Friedman’s blog http://crazorsharp.blogspot.com/2009/07/passing-objects-using-ref-keywordwait.html , but why it’s impossible pass a custom type as the actual argument when the formal argument of the object type uses the ref keyword?

As an example:

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();

        changeMe(p); // compiles
        changeMeByRef(ref p); // throws error

        object pObject = (object)p;
        changeMeByRef(ref pObject); // compiles
    }


    public static void changeMeByRef(ref object obj)
    {
        Person p = (Person)obj;
    }

    public static void changeMe(object obj)
    {
        Person p = (Person)obj;

    }
}

public class Person
{
}

Thanks.

ps I just changed the signature to:

public static void changeMeByRef <T> (ref T obj), where T: Person

this compiles for changeMeByRef (ref p);

+5
source share
4 answers

, , , . :

public void Foo(ref object x)
{
    x = "hello";
}

...

// This doesn't compile, fortunately.
Stream y = null;
Foo(ref y);

y ? , . , . IList<T> .NET 4.0.

ref .

+8

ref . , .

+2
+1

do it. it is easier.
      ChangeMe (p); // compiles
      changeMeByRef (ref (Object) p); // this time it should not cause errors.

0
source

All Articles