static void Main() { // Declare a class instance box1: Box box1 = new Box(30.0f, 20.0f); // Declare an interface instance dimensions: IDimensions dimensions = box1; // The following commented lines would produce compilation // errors because they try to access an explicitly implemented // interface member from a class instance: //System.Console.WriteLine("Length: {0}", box1.getLength()); //System.Console.WriteLine("Width: {0}", box1.getWidth()); // Print out the dimensions of the box by calling the methods // from an instance of the interface: System.Console.WriteLine("Length: {0}", dimensions.getLength()); System.Console.WriteLine("Width: {0}", dimensions.getWidth()); }
static void Main(string[] args) { SampleClass sc = new SampleClass(); IControl ctrl = (IControl)sc; ISurface srfc = (ISurface)sc; // The following lines all call the same method. sc.Paint(); ctrl.Paint(); srfc.Paint(); SampleClass2 obj = new SampleClass2(); //obj.Paint(); // Compiler error. IControl c = (IControl)obj; c.Paint(); // Calls IControl.Paint on SampleClass. ISurface s = (ISurface)obj; s.Paint(); // Calls ISurface.Paint on SampleClass. //======================================================= // Declare a class instance box1: Box box1 = new Box(30.0f, 20.0f); // Declare an instance of the English units interface: IEnglishDimensions eDimensions = (IEnglishDimensions)box1; // Declare an instance of the metric units interface: IMetricDimensions mDimensions = (IMetricDimensions)box1; // Print dimensions in English units: System.Console.WriteLine("Length(in): {0}", eDimensions.Length()); System.Console.WriteLine("Width (in): {0}", eDimensions.Width()); // Print dimensions in metric units: System.Console.WriteLine("Length(cm): {0}", mDimensions.Length()); System.Console.WriteLine("Width (cm): {0}", mDimensions.Width()); //======================================================= Box2 box2 = new Box2(30.0f, 20.0f); IMetricDimensions mDimensions2 = (IMetricDimensions)box2; System.Console.WriteLine("Length(in): {0}", box2.Length()); System.Console.WriteLine("Width (in): {0}", box2.Width()); System.Console.WriteLine("Length(cm): {0}", mDimensions2.Length()); System.Console.WriteLine("Width (cm): {0}", mDimensions2.Width()); //======================================================= // Declare a class instance box1: Box3 box3 = new Box3(30.0f, 20.0f); // Declare an interface instance dimensions: IDimensions dimensions = (IDimensions)box3; // The following commented lines would produce compilation // errors because they try to access an explicitly implemented // interface member from a class instance: //System.Console.WriteLine("Length: {0}", box1.getLength()); //System.Console.WriteLine("Width: {0}", box1.getWidth()); // Print out the dimensions of the box by calling the methods // from an instance of the interface: System.Console.WriteLine("Length: {0}", dimensions.getLength()); System.Console.WriteLine("Width: {0}", dimensions.getWidth()); }