-2
[Fact]
public void On_the_hour()
{
    var sut = new Clock(8, 0);
    Assert.Equal("08:00", sut.ToString());
}

I want to create class Clock with contructor which has parameters hours and minutes.

After calling it in another class(code above) how to return values? So, when i call Clock.ToString() i want to receive "hours:minutes"

public class Clock
{
    public int Hours;
    public int Minutes;

    public Clock(int hours, int minutes)
    {
        Hours = hours;
        Minutes = minutes;
    }
}
SonDy
  • 49
  • 5
  • 2
    [The Manual](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method) provides – Franz Gleichmann May 26 '21 at 10:25
  • Does this answer your question? [Why do I need to override ToString?](https://stackoverflow.com/questions/33166889/why-do-i-need-to-override-tostring) and [Override .ToString method c#](https://stackoverflow.com/questions/18200427/override-tostring-method-c-sharp/18200481) –  May 26 '21 at 10:26

1 Answers1

1

You have to override the ToString() method with desired implementation.

For padding with zeros you can use $"{Hours:00}:{Minutes:00}".

public class Clock
{
   public int Hours;
   public int Minutes;

   public Clock(int hours, int minutes)
   {
       Hours = hours;
       Minutes = minutes;
   }
    
   public override string ToString()
   {
       return $"{Hours:00}:{Minutes:00}";
   }
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128