Wednesday, April 27, 2011

Runtime polymorphism and compile time polymorphism

private void LogError(TextWriter tw, string msg)
{
tw.WriteLine(msg);
}

StreamWriter and StringWriter both derive from the abstract TextWriter base class. They both implement the WriteLine method. Depending on the type of the instance you pass into this method, it'll either write the message to a stream or to a string. LogMessage doesn't know or care which.

"With runtime polymorphism, the selection of a method for execution is based on the actual type of the object whose reference is stored in a reference variable, and not on the type of the reference variable on which the method is invoked."