I hope the title of this question summarizes the problem accurately. Here are the details:
I have two classes that share several properties and related methods, let’s MyFirstClass and MySecondClass. So, I put this intersecting set of properties into an abstract class that both my classes inherit from: MyAbstractBaseClass.
So far, so good. However, in a method elsewhere in my code, I am manipulating these shared properties and would like to be able to pass instances of both MyFirstClass and MySecondClass to this method by reference. Something like:
result1 = myMethod(ref MyFirstClass);
result2 = myMethod(ref MySecondClass);
I have tried using MyAbstractBaseClass as the parameter type for my method:
public bool myMethod(ref MyAbstractBaseClass anObject)
But this is not accepted by the compiler. I have also tried to extract the interface from MyAbstractBaseClass and have both MyFirstClass and MySecondClass inherit from MyAbstractBaseClass and implement the interface, like so:
public class MyFirstClass : MyAbstractBaseClass, IMyAbstractBaseClass
public class MySecondClass : MyAbstractBaseClass, IMyAbstractBaseClass
I was then expecting that the myMethod would be able to operate on both classes, if I make the parameter of the interface of type IMyAbstractBaseClass (after all, in OOP you’re supposed to code against interface when possible).
public bool myMethod(ref IMyAbstractBaseClass anObject)
IMyAbstractBaseClass myObject = new MyFirstClass();
result1 = myMethod(ref myObject);
This isn’t working either. The compiler says it is not possible to convert MyFirstClass to IMyAbstractBaseClass, which seems odd to me, because MyFirstClass implements the Interface and therefore I should be able to treat all objects of this class as type interface, no?
What am I missing here?
Do the parameters really need to be passed by ref?
If they are reference types (i.e. classes) (and they are), and you are only setting properties on them, then they do not need to be passed by reference. (Passing a reference by referene is having a pointer to a pointer)
Only in cases where you will be replacing the whole object do you need the ref:
myMethod2() will work exactly as you want.