jaewaen
jaewaen

Reputation: 33

How to return a string using methods

I am writing a class called Television that does a few simple controls, but I am running into an issue with my ToString method. "'Television.ToString()': not all code paths return a value". How would I go about returning either message? Any help is appreciated greatly, thank you.

class Television
{
    private string manufacturer;
    private int screenSize;
    private bool powerOn = false; // the power is off by default
    private int channel = 2;  // channel is default set to 2
    private int volume = 20;  // volume default set to 20

    public Television (string manu, int size) // The purpose of this constructor is to initialize the manufacturer and screen size fields.
    {
        manufacturer = manu;
        screenSize = size;
    }

    public int GetVolume() // accessor method that returns volume
    {
        return volume;
    }

    public int GetChannel() // accessor method that returns channel
    {
        return channel;
    }

    public string GetManufacturer() // accessor method that returns manufacturer
    {
        return manufacturer;
    }

    public int GetScreenSize() // accessor method that returns screen sizes
    {
        return screenSize;
    }

    public void SetChannel(int userChannel) // mutator method that changes the channel
    {
        Console.WriteLine("What channel would you like to watch?: ");
        userChannel = int.Parse(Console.ReadLine());
        userChannel = channel;
    }

    public void power() // mutator method that turns the power on/off
    {
        powerOn = !powerOn; 
    }

    public void IncreaseVolume() // mutator method that increases volume by 1
    {
        volume = volume + 1;
    }

    public void DecreaseVolume() // mutator method that decreases volume by 1
    {
        volume = volume - 1;
    }

    **public string ToString()
    {
        if (powerOn == false) {
        Console.WriteLine("A " + screenSize + " inch " + manufacturer + " has been turned off.");
        }
        else if (powerOn == true)
        {
        Console.WriteLine("A " + screenSize + " inch " + manufacturer + " has been turned on.");
        }**
    }
}

}

Upvotes: 0

Views: 55

Answers (1)

user12031933
user12031933

Reputation:

ToString should override the base method to respect the polymorphism design and it must return a string but you return nothing:

public override string ToString()
{
  string str = "A " + screenSize + " inch " + manufacturer + " has been turned ";
  return str + ( powerOn ? "on." : "off." );
}

Or:

public override string ToString()
{
  return $"A {screenSize} inch {manufacturer} is turned {(powerOn ? "on" : "off")}.";
}

Therefore you can use:

var television = new Television();

Console.WriteLine(television.ToString());

MessageBox.Show(television.ToString());

label.Text = television.ToString();

Upvotes: 5

Related Questions