Question:

Given an instance circle of the following class:

public sealed class Circle {
  private double radius;
  
  public double Calculate(Func<double, double> op) {
    return op(radius);
  }
}

write code to calculate the circumference of the circle, without modifying the Circle class itself.

Answer:

The preferred answer would be of the form:

circle.Calculate(r => 2 * Math.PI * r);

Since we don’t have access to the private radius field of the object, we tell the object itself to calculate the circumference, by passing it the calculation function inline.

A lot of C# programmers shy away from (or don’t understand) function-valued parameters. While in this case the example is a little contrived, the purpose is to see if the applicant understands how to formulate a call to Calculate which matches the method’s definition.

Alternatively, a valid (though less elegant) solution would be to retrieve the radius value itself from the object and then perform the calculation with the result:

var radius = circle.Calculate(r => r);
var circumference = 2 * Math.PI * radius;

Either way works. The main thing we’re looking for here is to see that the candidate is familiar with, and understands how to invoke, the Calculate method.


Keywords:

© 2017 QuizBucket.org