passing object reference to the method

P

puzzlecracker

Say I pass an object of a class (reference value I suppose) to a
method, and I want to pass it by reference. Do I need to preappend
it with ref.

public interface IFoo{}

public class Foo:IFoo{

}

void FromHere()
{

Foo f=new Foo();
Here(ref f);

}

void Here(ref IFoo f )
{
//do something with f
}

Is ref redundant or error-prone. In my scenerio I have a lot of
overload for Here-like function,
and compiler screams that it cannot convert IFoo to char (latter
beeing void Here(ref char c) )


Thanks
 
A

Anthony Jones

puzzlecracker said:
Say I pass an object of a class (reference value I suppose) to a
method, and I want to pass it by reference. Do I need to preappend
it with ref.

public interface IFoo{}

public class Foo:IFoo{

}

void FromHere()
{

Foo f=new Foo();
Here(ref f);

}

void Here(ref IFoo f )
{
//do something with f
}

Is ref redundant or error-prone. In my scenerio I have a lot of
overload for Here-like function,
and compiler screams that it cannot convert IFoo to char (latter
beeing void Here(ref char c) )

Stop using ref, both in the signature of the Here method and in calling it.

The purpose of ref is so that you can modify the variable which is used in
the calling of a function and that is a rare requirement.

void FromHere()
{
Foo f = null;

Here(ref f);
}

void Here(ref Foo pf)
{
pf = new Foo();
}


The f variable in the caller would now point to a new Foo object. However a
better style is:-

void FromHere()
{
Foo f = Here();
}

void Here()
{
return new Foo();
}


If you Here function OTH merely needs to use an existing objec then:-

void FromHere()
{
Foo f = new Foo();
f.SomeProperty = "Old Value";
Here(f);
Console.WriteLine(f.SomeProperty);

}

void Here(Foo pf)
{
pf.SomeProperty = "New Value";
}

Whilst the reference to a the foo object is passed by value the reference
now in pf points to the same instance of Foo as f does. Hence the console
write will output "New Value".

It is rare the ref is useful.

The reason you were getting an error was you had some overload signatures
like:-

void Here(Foo pf) { }
void Here(ref Char c) { }

and you calling like:-

Here(ref f)

When trying to determine the function signature to call the compiler has to
honor the order of ref parameters over the the types. Hence the closest
match was ref Char c but pf wound implicit coerce to a char.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top