BLOG.CSHARPHELPER.COM: Refine a class implementing an interface to allow access to the interface's members in C#
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.
Comments