|
I am writing a simple raytracer in C# as a way of learning the language - but have run into a problem: I have a parent class called "Primitive" which has an "Intersection" function. I have multiple child classes, for example "Sphere" which overwrite the "Intersection" function with "new public Intersection... etc..." as their intersection methods are all quite different. This works fine for single instances - but when I create an arraylist of primitives, such as Spheres and Planes, and the iterate through them with a foreach like this: ArrayList PrimList = new ArrayList(); Sphere sphere = new Sphere (); PrimList.Add (sphere); Plane plane = new Plane(); PrimList.Add (plane); foreach (Primitive p in PrimList) { i =p.Intersect (x); } This will always use the parent intersect function and not the appropriate child function. :/ I think it's because the Spheres are being recasted to Primitives by the foreach function.... Is there a way around this such that the correct intersection method is used? |
Loading
AlanPosted May 8, 2008, 7:25 PM
It should work as long as you declare the Intersect() method in the Primitive class as 'virtual' and include the 'override' keyword in the declarations of the same method in the Sphere and Plane class.
The method which is chosen will then correspond to the runtime type of each Primitive object in the ArrayList.