2

I have an Abstract class Animal, which stores some common fields, e.g name, health. I have a number of animal classes e.g Tiger, but I also have a class Fish which has an additional field the other animal classes don't have, canSplash.

I then have a list of Animal objects. I can access the common fields, but I cannot access the canSplash field for Fish. I am looking for help to accessing a concrete classes specific fields from an Abstract Class.

class Zoo
{
    public List<Animal> animals = new List<Animal>();

    public Zoo()
    {
        animals.Add(new Monkey());
        animals.Add(new Tiger());
        animals.Add(new Fish());
    }

    public static void displayZooPopulation()
    {
        foreach (var a in animals)
        {
            if (a.species == "fish" && a.CanSplash)
            {
                Console.WriteLine("{0} can splash",a.Name);
            }
        }
    }
}

class Fish : Animal {
    private bool canSplash
    public bool CanSplash { get; set; }
}
4
  • why is canSplash bool while CanSplash float? Why is canSplash private?
    – jdweng
    Jul 17, 2016 at 13:11
  • canSplash is private because you use gets and sets to access it. Sorry, float was a mistake I made typing this question.
    – ecclesm
    Jul 17, 2016 at 13:13
  • 2
    remove the field: private bool canSplash, you needn't it.
    – M.Hassan
    Jul 17, 2016 at 13:18
  • 1
    I f you make canSplash private you need a method to extra property so other classes can access to property.
    – jdweng
    Jul 17, 2016 at 13:22

2 Answers 2

5

Simple answer would be, check the type by safely cast to it and check if it is not null:

var fish = a as Fish;
if (fish != null && fish.CanSplash)
{
    Console.WriteLine("{0} can splash",a.Name);
}

This is perfectly okay if you only have one child class which has this specific behavior. But consider you have other child classes of animals which also are able to splash, like let's say an elephant, then you have to check for the elephant's class also if you want to find all animals in your zoo which can splash.

A better approach is to use an interface for such things like ISplashable:

public interface ISplashable
{
    bool CanSplash { get; }
}

Now implement this interface in all of your child classes which should be able to splash:

public class Fish : Animal, ISplashable
{
    // ...

    public bool CanSplash { get; set; }  // this also implements CanSplash { get; }

    // ...
}

public class Elephant : Animal, ISplashable
{
    // ...

    public bool CanSplash { get { return true; } }

    // ...
}

Now you can check against that interface instead of the concrete class:

var splasher = a as ISplashable;
if (splasher != null && splasher.CanSplash)
{
    Console.WriteLine("{0} can splash",a.Name);
}
1
  • Wow thanks for the extended answer with interfaces, that's not only really helpful in this case, but has also made the use of interfaces so much clearer to me. Thank you very much!
    – ecclesm
    Jul 17, 2016 at 14:07
0

//remove the static keyword, for you can't access animals (or animals should be static)

check type of a , and take your action

The method can be:

 public   void displayZooPopulation() 
    {
        foreach (var a in animals)
        {
            if ( a is Fish)
            {
//here sure "a" is not null, no need to check against null
                var fish = a as Fish;
                //  if (a.species == "fish" && (Fish) a.CanSplash)
                if ( fish.CanSplash)
                {
                    Console.WriteLine("{0} can splash", a.Name);
                }
            }
        }
    }

BTW, you say that Animal is abstract class , where is implementation of abstract methods in Fish class :)

3
  • In this case you are doing the type checking two times which is not necessary. Your approach is about the old pattern if (a is SomeClass) { var c = (SomeClass) a; ... which is inefficient.
    – abto
    Jul 17, 2016 at 14:00
  • I concentrated in the scope of OP implementation , check the type only once (not twice) to take necessary action. your modification using Interface is good for large complex model, for simple class model you needn't. BTW,in c# 6, for checking against null we can use: if (splasher?.CanSplash) :)
    – M.Hassan
    Jul 17, 2016 at 14:22
  • Your "concentration" is exactly what a safe typecast is doing. Your if (a is Fish) statement is unnecessary, especially if you want to use the new C#6 feature: var fish = a as Fish; if (fish?.CanSplash) .... And you're right, interfaces are not necessary in a simple design, but I stated this in my answer...
    – abto
    Jul 17, 2016 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.