Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Normally I do this: if (Animal is Dog) { Doc d = (Dog)Animal; // d. etc.. } else

ID: 644002 • Letter: N

Question

Normally I do this:

if (Animal is Dog)
{
    Doc d = (Dog)Animal;
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
Is this a good way or are there better ways to implement this code above (performance, ...) ?

Should it be like this?:

Dog d = Animal as Dog;

if (d != null;)
{
    // d. etc..
}
else if (Animal is Cat)
{
    Cat c = (Cat)Animal;
    // c. ....
}
Or maybe like this?:

Dog d = Animal as Dog;
Cat c;

if (d != null;)
{
    // d. etc..
}
else if ((c = Animal as Cat) != null)
{
    // c. ....
}
Or maybe something else?

Explanation / Answer

Ideally, you should aim for just:

Animal.DoWhateverYouNeedDone();
That is, implement the polymorphic behavior (if it's a dog, do a dog thing, if it's a cat, do a cat thing, etc.) in the classes themselves. So instead of this:

if (Animal is Dog) {
var d = Animal as Dog;
d.Bark();
}
if (Animal is Cat) {
var c = Animal as Cat;
c.Meow();
}
Do this:

Animal.Speak();

// where:

public class Dog: Animal {
public void Speak() {
this.Bark();
}
// ---- snip -----
}
public class Cat: Animal {
public void Speak() {
this.Meow();
}
// ---- snip -----
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote