Reputation: 13
I got this lines of code (C#)
Console.WriteLine("This is you {0}.", someclass.name);
What I would like use is this part:
private void ConsoleWriteColor(ConsoleColor color, string text)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
Problem is, i cannot transfer the string with {0} values into the parameter text from ConsoleWriteColor.
Solution:
string para = string.Format("Some text {0}",parameter);
Upvotes: 0
Views: 2777
Reputation: 22038
You also should check the C# 6.0 Interpolated strings feature. I think it's more readable (which you prefer, I hope)
You don't need to change the method on formatting or plain:
private void ConsoleWriteColor(ConsoleColor color, string text)
{
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ResetColor();
}
string name1 = "Arthur";
string name2 = "David";
ConsoleWriteColor(ConsoleColor.Red, $"Hello {name1} and {name2}"); <-- notice the $
Upvotes: 1
Reputation: 216273
You can pass a params argument to your ConsoleWriteCOlor like this
private void ConsoleWriteColor(ConsoleColor color, string text, params object[] prms)
{
Console.ForegroundColor = color;
Console.WriteLine(string.Format(text, prms));
Console.ResetColor();
}
Now you can call it like this
ConsoleWriteColor(ConsoleColor.DarkRed, "Hello {0} It is {1}", "Steve", DateTime.Today.DayOfWeek.ToString());
Beware that this approach has no checking on the correct number of parameters passed to the function. You could pass less arguments than those expected by the format string and get an exception (albeit the same exception happens also writing directly the string.Format without this function)
Upvotes: 2
Reputation: 7706
Use string.Format("Some text {0}",parameter);
this will insert your parameter and return string. And here is example how you can do it:
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine("Hello, world!");
ConsoleWriteColor(ConsoleColor.Red,"Hello {0} and {1}","Arthur","David")
}
private static void ConsoleWriteColor(ConsoleColor color, string text,params object[] a)
{
Console.ForegroundColor = color;
Console.WriteLine(string.Format(text,a));
Console.ResetColor();
}
Upvotes: 1