Maha

Maha

  • NA
  • 0
  • 326.1k

IFormattable

Sep 17 2012 3:32 AM
This program is given in the following website (http://www.c-sharpcorner.com/uploadfile/prvn_131971/polymorphism-in-C-Sharp/). Is there any simple example program which can demonstrate the use of IFormattable like in this example? Problem is highlighted.

// notice the comments/warnings in the Main
// calling overridden methods from the base class
using System;
class TestClass
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double Area()
{
return x * x;
}
}
class Cube : Square
{
// Constructor:
public Cube(double x) : base(x)
{
}
// Calling the Area base method:
public override double Area()
{
return (6 * (base.Area()));
}
}
public static void MyFormat(IFormattable value, string formatString)
{
Console.WriteLine("{0}\t{1}", formatString, value.ToString(formatString, null));
}
public static void Main()
{
double x = 5.2;
Square s = new Square(x);
Square c = new Cube(x); // This is OK, polymorphic
// a base reference can refer to the derived object
Console.Write("Area of Square = ");
MyFormat(s.Area(), "n");
Console.Write("Area of Cube = ");
MyFormat(c.Area(), "n");
// ERROR: Cube q = new Square(x);
// Cannot implicitly convert type 'TestClass.Square' to 'TestClass.Cube'
Cube q1 = (Cube)c; // This is OK, polymorphic
Console.Write("Area of Cube again = ");
MyFormat(q1.Area(), "n");
Console.ReadLine();

// try uncommenting the following line and see if it works
// Cube q2 = (Cube) new Square(x);
// This compiles but is this OK? NO!
//Runtime Exception occurs here: System.InvalidCastException:
//An exception of type System.InvalidCastException was thrown.
// A derived reference should not be transformed from base object,
// since the orphaned parts may occur in the derived.
// Cube constructors those may be necessary had not worked up to now for q2.
// C# compiles code but gives an exception during runtime
}
}

Answers (4)