1
Answer

Writing a raytracer to learn C#.... hit a problem with inheritance / iteration:

Bob

Bob

16y
2.4k
1
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?
Answers (1)