Error passing a class instance by reference

  • Thread starter Thread starter AA
  • Start date Start date
A

AA

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
 
AA said:
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
}

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

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!
 
Back
Top