I want to hide a StopWatch label when its equals to 0, How can I do this using conditional operator?
using System;
using System.Diagnostics;
using System.Threading;
namespace FileTransfer_Socket_Client
{
class transferRate
{
static Stopwatch stopWatch = new Stopwatch();
public static void timeLeft()
{
Thread StimeLeft = new Thread(Start);
StimeLeft.Start();
}
private static void Start()
{
int rate = 0;
int left = 0;
int prevSum = 0;
stopWatch.Start();
while (fileTransfer.client.Connected)
{
if (fileTransfer.sum != 0)
{
rate = (fileTransfer.sum-prevSum)/1024;
left = ((fileTransfer.fileSize - fileTransfer.sum)/ 1024) / rate;
TimeSpan t = TimeSpan.FromSeconds(left);
Program.mainForm.AppendLabel(string.Format("{0}kb/s timeleft: {1:D2}:{2:D2}:{3:D2}", rate, t.Hours, t.Minutes, t.Seconds));
prevSum = fileTransfer.sum;
Thread.Sleep(1000);
}
}
stopWatch.Stop();
stopWatch.Reset();
}
}}
While there are more “interesting” ways to get this done, an
if/elseis the most basic way:Note that we can write it like this, and avoid the duplication of the method call:
Or we could use a ternary (conditional operator):
Or we could put it all nicely inside a method:
Happy coding.