Home > other >  Implement the "TransformToElephant" method so that the program displays the line "Ele
Implement the "TransformToElephant" method so that the program displays the line "Ele

Time:10-06

The program displays the string "Fly" on the screen, and then continues to execute the rest of the code. Implement the TransformToElephant method so that the program displays the line "Elephant", and then continues to execute the rest of the code without first displaying the line "Fly".

using System;

namespace ConsoleAppTransformToElephant
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TransformToElephant();
            Console.WriteLine("Fly");
            //... custom application code
        }

        static void TransformToElephant()
        {
            //... write your code here 
        }
    }
}

CodePudding user response:

This is a classic job interview question. And it is a trap. In my opinion the only correct answer is to explain why the given code doesn't follow good coding style and that the requested change would make it even worse.

Relevant ideas are that methods should not have side-effects and that oop languages have specific mechanisms to implement polymorphism.

CodePudding user response:

On the one hand, it is written that the code should be written to the method. On the other hand, it is not written that I cannot create my own class. Without creating a class, I couldn't figure out how not to break the output

Use this code:

using System;
using System.IO;

namespace ConsoleAppTransformToElephant
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TransformToElephant();
            Console.WriteLine("Fly");
            //... custom application code
            Console.WriteLine("-----");
            Console.WriteLine("Fly");
            Console.WriteLine("End...");
            Console.Read();
        }

        static void TransformToElephant()
        {
            //... write your code here 
            Console.WriteLine("Elephant");
            Console.SetOut(new MyWriter());
        }

        class MyWriter : StringWriter
        {
            TextWriter defaultTextWriter = Console.Out;
            public override void WriteLine(string value) 
            {
                if (value == "Fly") { Console.SetOut(defaultTextWriter); }
            }
        }
    }
}

Result in console:
e

  • Related