[Code snippets] How to “refresh” a value in a C# Console Application

In this post I will be discussing how to refresh a value in C# Console applications.


While still in bed this morning,  I was skimming /r/csharp on Reddit and because it is so easy to just keep scrolling while on the phone, I happened to find a quite old subject. By old I mean six days with the latest reply being two days ago. That is old on the internet.

Anyway, the question was in essence if it is possible to refresh a value in a C# Console application. This got me intrigued, as I thus far have not worked too much with Console applications in this language, and did not know if it was possible. I read the answers, and because of the nature of /r/csharp, the preferred way to answer is not to spoon feed, but to give hints or link to places were one could get a push to figure out the answer oneself.

However, the original poster did not seem to get how this was to be done, so I kind of wanted to see if I could do it, because I like a challenge. Though it really was not a challenge, it was quite easy actually, it was kind of enjoyable, so I decided to play around a little with it.


As a programmer, generally the first thing you want to is to query ones favourite search engine, mine being Google (which I soon will write a blog post on how to properly use Google). The rule is, shorten your question into key terms and search away. So, I figured these were “refresh value console c#“, and sure enough, the first link was a StackedOverflow question that answered the question.

Since I did this after reading the answers on Reddit, I thought I would try to refresh a value in a Console application using the links provided by /u/TrikkyMakk and /u/wydok, both of which gave excellent answers. I will start of with the latter, as that was the shorter and slightly easier one, but also a little more restrictive.


/u/wydok’s answer was to use Console.Write() instead of Console.WriteLine(), because it does not automatically create a new line, but just keeps writing on the same line until it is told otherwise.

Because of how a C# Console application works, if it starts writing where other characters are, it simply writes over it – kind of like writing while having Insert on in for example Word. So, by starting the string inside the brackets with \r, the expression for Carriage Return, whatever is written in the Console will be overwritten by what is inside the string after \r. Here is an example using a Timer to automatically update the value.


// Declare an object called timer and the integer.
private static Timer timer;
private static int i = 0;
static void Main(string[] args)
{
// Set the timer to be a new Timer with an interval of 2 seconds.
timer = new Timer(2000);
// Everytime that interval has been reached, fire off this event.
timer.Elapsed += OnTimedEvent;
// The timer is now enabled and will start printing stuff.
timer.Enabled = true;
// Print the "first" value
Console.Write("{0}", i);
// This one waits for user input, as long as none is given, the progam will go on forever.
// (I.E. a key is not pressed)
Console.ReadKey();
// Will just flash by as the program will be closing.
Console.WriteLine("Terminating the application…");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// Increment the integer
i++;
// \r makes the console go back all the way on the row,
// and {0} prints out whatever the first value is on the other side of the comma (which in this case is the integer i).
Console.Write("\r{0}", i);
}

Note: If the new string is shorter than the old one, the new will only write over as much as it can, and leave the rest. For example, if the original string is “abcdefg” and the new is “\rABC” the final string will be “ABCdefg”.


 

While the above is cool and all, it might not be specifically what the original poster needs, so I also tried the answer that /u/TrikkyMakk gave, with great success. Since the answer was a little on the short side – being nothing but a link – I opened the link and followed the steps provided by Microsoft in said link, which included a very cool method using Console.SetCursorPosition(), which allows the programmer to specify where the Console should write next (as long as it is on the screen).

After doing that, I played around a little myself and decided to go for a Timer again, some Randoms and a list of all the letters in the alphabet. Because of how the Random object works, it is crucial only one Random object is used for all the random operations, otherwise, if two were to be used, both are highly likely to produce the same number, which is not really what is wanted.

What I got is a weird Console application that write random numbers in a 6 x 6 square.


// Declaring the integers used for positioning.
protected static int origingalRow;
protected static int originalColoumn;
protected static void WriteAt(string s, int x, int y)
{
// If an exception (error) is thrown insde the catch,
// the program will, in fact, not crash and whatever code inside catch will be run.
try
{
// Sets the position to write on and then writes there.
Console.SetCursorPosition(originalColoumn + x, origingalRow + y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
// Clear the Console and write the exception message.
Console.Clear();
Console.WriteLine(e.Message);
}
}
// For the fun of it, let's create a Timer.
protected static Timer timer;
static void Main(string[] args)
{
// Clear screen, then save the top and left coordinates,
// which should be top of the screen at the moment
Console.Clear();
originalColoumn = Console.CursorLeft;
origingalRow = Console.CursorTop;
// Instantiate timer with an interval of 0.2 seconds.
timer = new Timer(200);
// Everytime that interval's been reached, fire off this event.
timer.Elapsed += advancedTimer_Elapsed;
// Enable the timer to start printing stuff.
timer.Enabled = true;
// This one waits for user input, as long as none is given, the progam will go on forever.
// (I.E. a key is not pressed)
Console.ReadKey();
// Will just flash by as the program will be closing.
Console.WriteLine("Terminating the application…");
}
// Create a list of all the letters in the English alphabet
protected static List<string> englishAlphabet = new List<string>()
{
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k","l","m", "n", "o","p","q","r","s","t","u", "v", "x", "y", "z"
};
private static void advancedTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// Instantiate a Random object. Only one, though!
Random random = new Random();
// A letter somewhere from the English alphabet.
string letter = englishAlphabet[random.Next(0, englishAlphabet.Count)];
// Get the coordinates
int x = random.Next(0, 5);
int y = random.Next(0, 5);
// Print the letter at x and y.
WriteAt(letter, x, y);
}


In conclusion, it is possible to refresh a value in a C# Console application. If a whole row is to be refreshed, and that is the last and only row to be altered, one can use Console.Write(“\rWrites over whatever else was here.”). If a more complex overwrite or refresh has to be done, one can use the Console.SetCursor()-method to specify where to write.

Happy coding!

 

[Code snippets] How to “refresh” a value in a C# Console Application