0

I got a class Fruit that has a lot of variables: mass, taste... etc. I got a class Apple that has a few more variables added to it: size, texture... etc.

I wrote a simple function that loads the Fruit variables, and don't want to copy all of it to fill the Apple variables too.

public void ReadFruitData(string Name, ref Fruit newFruit);

public void ReadAppleData(string Name, ref Apple newApple);

I wish to call ReadFruitData from ReadAppleData, but not quite sure how to do it, since I can't pass newApple as newFruit

class Apple : Fruit

Any ideas how I can achieve that?

Vimal CK
  • 3,543
  • 1
  • 26
  • 47
HitWRight
  • 121
  • 8

4 Answers4

5

Well, in fact you can.

If your Apple class inherits Fruit, you are able to pass in an instance of a deriving type into that method. The actual problem is the use of the ref keyword.

Try to write out ref. Don't use it if you don't really need to, or use the return value to give back a newly created instance.

If you just update values in newApple, you can omit ref and it works:

public void ReadFruitData(string Name, Fruit newFruit)
{ }

public void ReadAppleData(string Name, Apple newApple)
{
    ReadFruitData(Name, newApple);
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
4

Inside ReadAppleData use a temporary variable to do it:

Fruit TempFruit = (Fruit)newApple;
ReadFruitData(Name, ref TempFruit);
// carry on with the rest of your code

Note: This is a workaround to that pesky compiler complaining that The best overloaded method match for... has some invalid arguments if you try to send the newApple directly.
It will not fit any situation.

As Patrick Hofman mentioned on the comments, if the ReadFruitData assigns a new instance of Fruit to the ref parameter, this is not the solution for you. (and in that case you should probably use out instead of ref).

Here is an example of when not to use this and an example of when you can use it.

Community
  • 1
  • 1
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
2

You don't need the ref keyword.

You are using an reference type. If you modify the Fruit or Apple inside those two methods, you modify the original Fruit or Apple.

If you would have a method where you pass in an int or an bool without defining them as ref parameters and you modify the value inside the method, the value of the original variables will not change.

See:

Community
  • 1
  • 1
whymatter
  • 755
  • 8
  • 18
-3

Modify your function definition of ReadFruitData(string Name, ref Fruit newFruit) to ReadFruitData(string Name, ref Object newFruit)

And inside your method, do a cast.

e.g. ReadFruitData(string Name, ref Object newFruit) { Fruit myFruit = newFruit as Fruit; OR Apple myApple = newFruit as Apple; }

Hope this helps. :)