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);
changeMeByRef(ref p);
object pObject = (object)p;
changeMeByRef(ref pObject);
}
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);
source
share