Refine a class implementing an interface to allow access to the interface's members in C#

The example Define and implement an interface in C# shows how to make an IVehicle interface that defines a MaxSpeed property. The Car class implements IVehicle but you can't access a Car's MaxSpeed property directly; you can only access it through the IVehicle interface.

This example adds the following code to the Car class to allow you access the MaxSpeed property directly for a Car object.
// Delegate MaxSpeed to IVehicle.MaxSpeed.
public int MaxSpeed
{
get { return (this as IVehicle).MaxSpeed; }
set { (this as IVehicle).MaxSpeed = value; }
}

This code delegates the new MaxSpeed property to the one provided by the IVehicle interface. It converts the current object into a reference to an IVehicle and then uses its MaxSpeed property.

The main program still cannot access the object's NumCupholders property from an IVehicle variable because NumCupholders is a property of the Car class not the IVehicle interface. For example, if the IVehicle were a Motorcycle or Rollerblade, it wouldn't have the NumCupholders property.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.