inherited object as ref

  • Thread starter Thread starter barkmaz
  • Start date Start date
B

barkmaz

Hey,

Can we send an inherited object into a function which requires its
base class as REF?

class y
class x : y
func DoSomething(ref y)
DoSomething(ref x);

gives an error. If I send object without Ref, then modifications on
object get lost when DoSomething func ends.

Can someone describe this for me? Thanks.
 
No to the first, since otherwise you could get the following:

void DoSomething(ref Y y) {
y = new Y();
}

X x = new X();
DoSomething(ref x);
// WTF! x isn't null, and doesn't hold an x (or subclass)... major
error!

However! I suspect you don't need "ref" here; as long as your object
is a class and not a struct, changes made to *properties* of the
object should persist after the call. But if you reassign the variable
entirely, then no: this won't be carried back over.

If you must use ref, then you'll need an appropriately typed variable:
Y y = x;
DoSomething(ref y);
x = (X) y; // pray that DoSomething returned an appropriate object

Alternatively, generics may be useful:

void DoSomething<T>(ref T t) where T : Y, new() {
t = new T(); // for some reason
}

DoSomething(ref x); // <X> is inferred from variable type


Hope this helps,

Marc
 
Sorry everyone, I had a silly mistake when applying this onto source.

So, it's solved now.
 
Thanks Marc, it was a silly error or my source so I had solved before
you wrote such detailed reply for me. :)
 
Can we send an inherited object into a function which requires its
base class as REF?

Yes, as long as you initialize the object passed before passing it. I'm sure
the exception told you that.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
Yes, as long as you initialize the object passed before passing it. I'm sure
the exception told you that.

Well, you can use a variable of the appropriate parameter type which
happens to hold a reference to an instance of the derived class, but
you *can't* use a variable which is of a derived type itself. So for
this method signature:

void MethodCall (ref object o)

This is valid:

object o = "foo";
MethodCall (ref o);

But this isn't:

string s = "foo";
MethodCall (ref s);

Jon
 
Ah yes. Thanks for clearing that bit up.

--

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 
Back
Top