Groups | Blog | Home
all groups > c# > september 2003 >

c# : Error passing a class instance by reference


AA
9/16/2003 10:20:52 PM
I have this simple class

public class Person
{
public Person(){}
public String Name = String.Empty;
public String LastName = String.Empty;
}

and this procedure that has one input parameter of type Object

public void FillPerson(ref Object inObj)
{
//do something with the object inObj
}


well, my problem is when I create a new instance of the class Person and
pass it to the procedure, something like this...

private void NewPerson()
{
Person PersonOne = new Person();
FillPerson(ref PersonOne); // In this line appear this error when I
compile...
//"Argument '1': cannot convert from
'ref Company.Person' to 'ref object'
// The best overloaded method match
for 'Company.FillPerson(ref object)' has some invalid arguments
}


but..... if i create a new object instance of type 'object' everything is
compiled ok.

private void NewPerson()
{
Person PersonOne = new Person();
Object PersonOneObj = PersonOne
FillPerson(ref PersonOneObj); // This work perfectly.
}


So, why I can pass my object Person as Object?

Thanks a lot

I really will apreciate your answer

AA

Jon Skeet
9/17/2003 8:40:57 AM
[quoted text, click to view]

<snip>

[quoted text, click to view]

Firstly, you should make sure you really need to pass it by reference
in the first place. It's important to understand the difference between
passing by reference and passing a reference by value. See
http://www.pobox.com/~skeet/csharp/parameters.html

Next, consider what would happen if the code for FillPerson were:

public void FillPerson (ref Object inObj)
{
inObj = "hello";
}

Now, if you were able to write:

Person p = new Person();
FillPerson (ref p);

then p would end up having a value which was a reference to a string,
not a person!

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
AddThis Social Bookmark Button