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

1538 views c#

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++;


Hopefully there's some way to do this.

answered question

2 Answers


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)

posted this

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))

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?


Please login first before posting an answer.