How can I have a dynamic property in c# - c#

I am creating a method that allows me to print a message in the console and to be able to change the color of the message in that same method.
I send 2 parameters to carry out this action, message (which is the message that is printed in the console) and color (which is the color that I want to be printed in the console)
I have my code like this:
public void Write(string message, string color = "White"){
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(message);
}
But I need ConsoleColor.White to grab my dynamic color as follows (similar to javascript): ConsoleColor [color];
How can I achieve this? Thanks in advance.
What I tried was the above: ConsoleColor[color];

ConsoleColor is an Enum, so the usual way to do this would be to take a ConsoleColor as the second parameter:
public void Write(string message, ConsoleColor color = ConsoleColor.White){
Console.ForegroundColor = color;
Console.WriteLine(message);
}
If you really need it to be a string, you can use Enum.Parse, but this runs the risk of a failed conversion if the caller passes an invalid color value:
public void Write(string message, string color = "White"){
Console.ForegroundColor = Enum.Parse<ConsoleColor>(color);
Console.WriteLine(message);
}
Or if you want a version that won't throw with a bad value:
public void Write(string message, string color = "White"){
Console.ForegroundColor = Enum.TryParse<ConsoleColor>(color, out ConsoleColor parsedColor)
? parsedColor : ConsoleColor.White;
Console.WriteLine(message);
}

Related

How do I make a program that gets a letter from the user and outputs something according to the letter?

Let me tell you more about this question:
So, I want to make a program that gets a letter from the user and according to the letter, if it is "R", outputs "It's Red!" in Red text, if it is "G", outputs "It's Green!" in Green text if it is "B", outputs "It's Blue!" in Blue text! But if it is not R, G, or B, then outputs that there is no color associated with this letter.
It is a C# Console App and this is what I've written for now:
char color;
Console.WriteLine("Enter a letter (R/G/B): ");
color = char.Parse(Console.ReadLine());
if(color==R)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Red!");
}
else if(color==G)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Green!");
}
else if (color==B)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.WriteLine("It's Blue!");
}
Console.ReadKey();
One more thing to mention is that I don't know how to write that other part where how to make it if "color" doesn't match R or G or B. I would be happy to know how to do that as well
It is just a little program I'm making out of boredom.
I tried to make something that if "color" is R, outputs that. But I'm not sure how to do that so any assistance regarding that would be great!
The following code should do the trick:
char color;
Console.WriteLine("Enter a letter (R/G/B): ");
color = char.Parse(Console.ReadLine());
if(color=='R')
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Red!");
}
else if(color=='G')
{
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Green!");
}
else if (color=='B')
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.WriteLine("It's Blue!");
}
else
{
Console.WriteLine("There is no color associated with this letter!");
}
Console.ReadKey();
Why not use an dictionary (key,value) where key is the letter, and value is the message.
You create it like so var dic = new Dictionary<char, string>();
And use it like so:
//dic.Add("key","Value");
var dic = new Dictionary<string, string>();
dic.Add("R","It's Red!");
dic.Add("G","It's Green!");
dic.Add("B)","It's Blue!");
//use .ToUpper() if the key is uppercase in order to ensure its not case sensetive
if(dic.TryGetValue(color.ToUpper(),out var message))
{
//output message
Console.WriteLine(message);
}
else
{
//output errormessag
}
You can add as many key/value as you want for each letter
Just copy and paste the following code ^^
Console.WriteLine(#"This task was a little bit changed by me.
Please write me if you need me to upgrade or explain smth.
And Sorry for english mistakes, it's not my mother language.
Enter a letter (R/G/B): ");
while (true) // it's gonna work everytime
{
try // smth in that "try" might have errors, there are no errors, just because "color" is not a char, but string
{
string color = Console.ReadLine().ToLower(); // i changes it from char to string, cause it does not make any sense
// command to lower makes all to lower case, so ("R" => "r", "BlaBLAbla" => "blablabla")
// that's your code, but we compare strings with "=="
if (color == "r")
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Red!");
}
else if (color == "g")
{
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Green!");
}
else if (color == "b")
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();
Console.WriteLine("It's Blue!");
}
else // "else" works if any other cases are true, so (if color is not "b", "g", "r")
{
Console.WriteLine("You need to chose from a letters (R/G/B): ");
}
}
catch (Exception ex) // in a case of error we print this too
{
Console.WriteLine("You need to chose from a letters (R/G/B): ");
}
}
Console.ReadKey();
Here's some tips on improving your code. When you have repetitive code that looks like:
if(color==R)
{
/* block of code */
}
else if(color==G)
{
/* block of code */
}
else if (color==B)
{
/* block of code */
}
else
{
/* block of code */
}
You might want to consider using a switch statement. But, that's not what I'm going to suggest.
Instead, I'm going to concentrate on your
/* block of code */
The same code is repeated in each block:
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine("It's Red!");
We folks in the software business love three letter acronyms. One of the ones you will here is the DRY Principle. In this case DRY stands for Don't repeat yourself. You are repeating your self in each block. If you decide to do something different, you'll need to update each of those blocks with the change.
Instead of this repetition, let's look at the code. There are three pieces of data that could represent what each block means:
BackgroundColor
ForegroundColor
Message to write out
So, let's create a class that represents that data:
public class MessageAndFormat
{
public ConsoleColor Foreground { get; set; }
public ConsoleColor Background { get; set; }
public string Message { get; set; } = string.Empty;
}
It's a simple class that has three properties. Now, let's write a method that consumes the data from a MessageAndFormat class instance:
public static void WriteMessageAndFormat(MessageAndFormat messageAndFormat)
{
Console.ForegroundColor = messageAndFormat.Foreground;
Console.BackgroundColor = messageAndFormat.Background;
Console.WriteLine(messageAndFormat.Message);
}
Instead of keying on a char, I'm going to do it on a single character string. The framework has endowed strings with more capabilities; in particular, you can do case-independent comparisons of strings (and I don't think you can with simple chars)
Instead of using if/then/else or using a switch statement, I'm going to use a Dictionary for my "what character - what action" logic. So, I'm going to declare and initialize that dictionary:
private static Dictionary<string, MessageAndFormat> colorMapping = new Dictionary<string, MessageAndFormat>(StringComparer.OrdinalIgnoreCase)
{
{"R", new(){Background = ConsoleColor.Black, Foreground = ConsoleColor.Red, Message = "It's Red!"} },
{"G", new(){Background = ConsoleColor.Black, Foreground = ConsoleColor.Green, Message = "It's Green!"} },
{"B", new(){Background = ConsoleColor.White, Foreground = ConsoleColor.Blue, Message = "It's Blue!"} },
};
Now I have the core of my logic encapsulated in an easy to read declarative data structure. The StringComparer.OrdinalIgnoreCase parameter to the dictionary constructor says "use case-ignoring logic when checking the key of this dictionary". As a result, a key of "r" will be treated the same as a key of "R".
When I was writing this code, I realized that it would be useful to let the user know that he/she had typed an unknown character. I also realized it would be nice to let the user know the program was quitting. So I declared and initialized these two variables as well:
private static MessageAndFormat Unknown = new() { Background = ConsoleColor.Gray, Foreground = ConsoleColor.White, Message = "Unknown" };
private static MessageAndFormat Quitting = new() { Background = ConsoleColor.Black, Foreground = ConsoleColor.White, Message = "Quitting" };
I changed up your program a bit. Now it runs forever, until the user types "Q" (to quit).
public static void Test()
{
Console.WriteLine("Type R/G/B for a color or Q to quit");
while (true)
{
string typedChar = Console.ReadKey(true).KeyChar.ToString();
if (string.Equals(typedChar, "Q", StringComparison.InvariantCultureIgnoreCase))
{
break; //quit the program
}
if (colorMapping.TryGetValue(typedChar, out var messageAndFormat))
{
WriteMessageAndFormat(messageAndFormat);
}
else
{
WriteMessageAndFormat(Unknown);
}
}
WriteMessageAndFormat(Quitting);
}
A few things to note:
This line reads a key typed (not a line of text).
string typedChar = Console.ReadKey(true).KeyChar.ToString();
The ReadKey call returns a bunch of information about what is typed. The KeyChar property gets the key as a char, which I turn into a single char string with ToString. The true parameter to the ReadKey call causes the key to be read, but not echoed to the console. Instead, when the user types R, he/she will simply see It's Red!
This line:
colorMapping.TryGetValue(typedChar, out var messageAndFormat)
Tries to get the MessageAndFormat value that corresponds to the typed character. If there's a match, it returns true. If there is no match, it returns false. The TryGet_Something_ pattern is pretty common in C# code.
If I start up the program and type "RGBXQ", I'll get this at the console (with each line in the appropriate colors:
Type R/G/B for a color or Q to quit
It's Red!
It's Green!
It's Blue!
Unknown
Quitting

handover ConsoleColor to method in C#

I want to write a short method that I can use to write one single line in the console colorful.
Currently I have to call my method like this:
ChangeConsoleColor("ABC", ConsoleColor.Yellow, ConsoleColor.Red);
But I want to be able to call it like this:
ChangeConsoleColor("ABC", Yellow, Red);
The perfectly working code I have looks like this:
static void Main(string[] args)
{
string myText = "ABCDEFG";
ChangeConsoleColor(myText, ConsoleColor.Yellow, ConsoleColor.Red);
System.Threading.Thread.Sleep(6000);
}
private static void ChangeConsoleColor(string Text, ConsoleColor BGC, ConsoleColor FGC)
{
Console.BackgroundColor = BGC;
Console.ForegroundColor = FGC;
Console.WriteLine(Text);
Console.ResetColor();
}
How do I need to change my code to get rid of the 'ConsoleColor' in the function call part?

How to pass color as parameter in c#?

I need to change font color many times in console app.
Instead of typing (or copying) each time :
Console.ForegroundColor = ConsoleColor.MyColor; in my code,
I want to type only
c(Red) or c(Yellow).
I thaough about something like this:
static void c(<???> myColor){
Console.ForegroundColor = ConsoleColor.MyColor;
}
How can I achieve that ?
Here is a method you can use to set the foreground color of your Console. I named the function as SetConsoleForeground but you can set it as you like such as c
/// <summary>
/// Sets Console Foreground color to the given color
/// </summary>
/// <param name="consoleColor">Foreground color to set</param>
private static void SetConsoleForeground Color(ConsoleColor consoleColor) {
Console.ForegroundColor = consoleColor;
}
Instead of passing c(Red) pass c(ConsoleColor.Red) and use parameter of type ConsoleColor enum in defination of method c()
public static void c(ConsoleColor myColor){
Console.ForegroundColor = myColor;
}
Call function using
c(ConsoleColor.Red);
MSDN ConsoleColor
I want to type only c(Red) or c(Yellow)
If you want to pass string called Red or Yellow and assign ForegroundColor to your console, then you can try below
public static void SetForegroundColor(string colorName)
{
//Set black as foreground color if TryParse fails to parse color string.
if(Enum.TryParse(ConsoleColor, colorName, out ConsoleColor color)
Console.ForegroundColor = color;
else
Console.ForegroundColor = ConsoleColor.Black;
}
Now you can pass color name as a string to this function, Like
SetForegroundColor("Red");
SetForegroundColor("Yello");
MSDN: Enum.TryPrase

Storing a colour in a variable for future use

I am writing a bit of a dungeon crawler as I learn my way through c#. I am using visual studio and the application is a "Console App (.NET Framework)". My problem is that I have an option in the main menu to change text colour and I am trying to find away to make this change all the other times I change the colour so that it returns to a set default.
I have tried to assign the colour to a variable, lets say, default and then do the Console.ForegroundColor = ConsoleColor.default; I looked online everywhere and can't find a fix.
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
Console.ForgroundColor = Console.Color.White;
// This needs to be default ^^
You can create a property that will of ConsoleColor which will considered as a default color.
Just Assign it when ever you want default color should set to Console.ForegroundColor
Something like,
public class Program
{
public static ConsoleColor DefaultColor { get; set; } = ConsoleColor.Black;
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("example");
//You can use DefaultColor whenever you want to assign default color to Foreground
Console.ForegroundColor = DefaultColor;
}
}

First time attempting programing. What am I doing wrong here?

enter image description hereFor my first try, I looked up some YouTube tutorials. One is showing how to create a Magic 8 Ball. I am following the instructions pretty much exactly but it won't work. When written like this it's fine:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
}
}
As you see I am trying to try create a String, not that I need one to do this. I just want to see how it works (So when I need it I don't need to re-type it and can just post this) But starting off it says "TellPeopleTheName must declare a body" I'm confused as this did not happen in the video. Not only that but when I cut and paste the code to join with it. For some reason it all breaks and no longer works:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
The entire bottom section is underlined in red saying "Invalid Token" and Writeline does not exist in this context". This confuses me more as this did not happen in the video either. What am I doing so wrong?
Thanks for the help and sorry for the nooby comments. I'm 20 and always wanted to learn coding but always been too busy working. Recently broke my back and now have plenty of time sitting doing nothing so I figured I would give it a shot.
This is mine (on top) and his (Bellow) and even after your help (I did go and re-watch and noticed I put String Void and not Static void) These problems still are here and I still don't understand. I apologise. I am really trying to learn and understand. This is a section I could skip and still make the 8-ball but I want to know why it does not work and how to fix it so then I know for when I do need to use this.
NEW FULL CODE:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
//This will tell people the name
static void TellPeopleTheName()
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
This line is out of place and doesn't actually do anything:
String Void TellPeopleTheName(String Text);
It's void, not Void. Casing matters.
You're giving it two return types, String and void. It either returns something or it doesn't.
That's a method header, but you're missing a method body. As a single line of code it doesn't make sense. Methods need to do something.
For example, a method might look like this:
void TellPeopleTheName(string text)
{
// write code in here to do something
}
Then you would invoke (call) that method somewhere from another method, when you want to perform that operation:
TellPeopleTheName("some text");
Or, in the case of a method which returns a string:
string TellPeopleTheName(string text)
{
// code which does something
return "some string";
}
Invoking it would be the same, but you could store the return value in a variable or otherwise use it in some way:
var someVariable = TellPeopleTheName("some text");
(Note: There are an ongoing variety of issues you may encounter even in trying what's described here. The difference between a static and non-static method come to mind, particularly if you try to call this from main(). Or the variety of ways you may return from a method or use the returned value. And so on. There's much to learn. Good luck!)
String Void TellPeopleTheName(String Text);
should be
void TellPeopleTheName(String Text)
{
}
That would take care of "missing body" error!
void should be in lowercase.
You are missing open/close brackets on the method too.
I notice a couple things you've missed in understanding.
What you've tried to do is write a method to write to the console the name of the program, but the method is not structured correctly.
The general structure of a method is...
AccessModifier static/non-static ReturnType MethodName (ParameterType ParameterName) {
//code to do something
}
An access modifier defines how accessible the method is to other code (as a starting programmer, just keep it as public until you become more advanced).
Putting static or nothing (non-static) is a little confusing for a beginner, if you'll be calling the method from Main (a static method) then it will need to be static, that's sufficient enough for a beginner's understanding for now.
The return type defines what the method should return back when the method is called.
The method name is just how the method is called, should be descriptive and clear what the method does.
A parameter type is the type of object that is being passed as a parameter for the method to use.
A parameter name is just a name, the name should easily explain what the parameter's purpose is for the method.
Following this structure, your method should look like...
public static void TellPeopleTheName(string text)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
If you want to make the method more "correct", then it would be...
public static void TellPeopleTheName(string nameOfProgram)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(nameOfProgram);
}
and you would call the method like this...
TellPeopleTheName("Magic 8 Ball. By: Conner Bostock");

Categories

Resources