When the formal argument of a method is of type 'object' it is possible, through inheritance, for the actual argument to be any object type. Once in the method the object can be cast to the type expected. All's fine.
If, however, the signature of the method has a formal argument of 'object', using the ref keyword i.e. methodname(ref object), the compiler throws an error stating that:
"The best overloaded method match for 'ByRefTest.Program.changeMeByRef(ref object)' has some invalid arguments. "Argument '1': cannot convert from 'ref ByRefTest.Person' to 'ref object'"
The difference between using or not using the ref keword when passing objects as parameters is explained very well in A. Friedman's blog http://crazorsharp.blogspot.com/2009/07/passing-objects-using-ref-keywordwait.html , but why is it not possible to pass a custom type as an actual argument when the formal argument of type 'object' 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);