I want to be able to print out three types of messages to the console: warnings, errors and success. For that each time I'd have to change the ForegroundColor of the console to either yellow, red or green, print out the message and change the color back. To make this faster I've decided to create a class (let's say Printer), which has three methods: Warning(message), Error(message), Success(message). Now my question is: should Printer be a struct or a class? I dont't plan to have any more fields/methods in this class.
-
Sounds like it could even be a static class.juharr– juharr2016-09-12 14:41:05 +00:00Commented Sep 12, 2016 at 14:41
-
Not really, at least I don't think so. I understand structs are most commonly used when you only want to group some simple values together. But I've also heard, that if a class does not modify its members, it should be a struct. I'm not sure how true that is, that's why I'm asking :)SalysBruoga– SalysBruoga2016-09-12 14:41:06 +00:00Commented Sep 12, 2016 at 14:41
-
2A static class is just saying that you have a method that is independant of any object. A regular class and a struct are both things that contain data and methods that are based on instatiations. The difference being where in memory the data is stored and how it gets passed. But from what you've stated here I see no reason that this wouldn't be a set of methods in a static class.juharr– juharr2016-09-12 14:48:18 +00:00Commented Sep 12, 2016 at 14:48
-
1I find this usually helps me decided if I've met all the crtieria for considering a struct: msdn.microsoft.com/en-us/library/ms229017(v=vs.110).aspxTVOHM– TVOHM2016-09-12 15:08:38 +00:00Commented Sep 12, 2016 at 15:08
-
1Consider locking if multiple threads can use the log printer. Otherwise you might end up with wrong foreground colors.Good Night Nerd Pride– Good Night Nerd Pride2016-09-12 15:31:30 +00:00Commented Sep 12, 2016 at 15:31
|
Show 5 more comments
1 Answer
It actually sounds like this should be a static class.
public static class Printer
{
public static void Warning(string message)
{
var currentColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(message);
Console.ForegroundColor = currentColor;
}
//Other similar methods here
}
Then you'd call it like this
Printer.Warning("This is a warning");