Can I call functions and variables from an object's parent class without casting the object's type explicitly?

1538 views c#
5

I want to go through a list of different objects that all derive from sub-classes of the same parent class and i only want to use stuff from the parent class anyways.

public class Foo{ public int a=0; }
public class Bar : foo{  }
public class Gun : foo{  }
public class Shotgun : Gun{  }
public class Rifle : Gun{  }

then what i would want to do later on:

object[] Array ={new Bar(),new Shotgun(),new Rifle()};
int index=0;
foreach(SubclassOfFoo obj in (Array as SubclassOfFoo[]))
{
    (Array[index] as SubclassOfFoo).a++;
    Console.WriteLine(obj.a);

    index++;
}

Hopefully there's some way to do this.

answered question

2 Answers

9

I would create a collection for base class Foo instead of object

List<Foo> array = new List<Foo>();
array.Add(new Bar());
array.Add(new Shotgun());
array.Add(new Rifle());

then you can use the collection directly without casting.

foreach(Foo obj in array)
{
    Console.WriteLine(obj.a);
    index++;
}

posted this
13

I would suggest to declare the array of the parent type:

Foo[] Array =new Foo{new Bar(),new Shotgun(),new Rifle()};

This way there is no casting required:

foreach(Foo obj in Array))
{
    obj.a++;
    Console.WriteLine(obj.a);
}

Since all subclasses inherit from Foo or from a child of Foo, this array can hold all children and grandchildren. Every subclass will have the property a. No casting is required

posted this

Have an answer?

JD

Please login first before posting an answer.