Answer the question
In order to leave comments, you need to log in
Did I understand correctly what UpCast and DownCast are for?
At first, I didn’t understand what it was for, if the inherited class already has what is in the base class, why all these upcasts.
Then I read about DownCast, the understanding comes that it is not clear why it is needed if the heir still cannot use the fields of the base class.
The only thing I understood is getting a reference to an object, here.
Then I decided to make the explanation more convenient for myself (After all, teachers are so smart, which means they explain in an abstruse way, no, to explain in an understandable language) to use double and int types:
I think that double is above int, since it can use int values, but also with floating point values, which means we can upcast int to double, but because int is below double, then we must apply downcast to convert the value with a dot to an integer (only int does not accept values with a dot) (While writing this message, I again did not understand why we need upcasts and downcasts)
So, now I understand that if we downcast'im or upcast'im, then we get a reference to the object, and not to class fields, right?
If all these scientific, dofiga clever phrases and functions were invented only to obtain a reference to class objects, and not fields, then did I understand correctly or did I go into some kind of wilds and did not understand anything?
Answer the question
In order to leave comments, you need to log in
the heir may be able to do something else . Those. downcasts - when you need to get to methods that are not described in the contract (those heirs can do something that the parent cannot do). Upcasts - when, on the contrary, we need to abstract from unnecessary details
For example:
public interface IClass {
void DoSomething();
}
public class Class1: IClass {
public void DoSomething() { ... }
}
public class Class2: Class1{
public void DoSomethingFaster() { ... }
}
...
public void InvokeWorker(IClass worker){
if (worker is Class2 class2Worker){
class2Worker.DoSomethingFaster()
}
else {
worker.DoSomething();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question