Create string in MessageBox or WriteLine - c#

I have a question, I don't really need it for the application at the moment but I was just curious.
Is there a way to create a string and fill it between the parentheses of WriteLine or Messagebox.Show ?
The code should then look something like this I think:
MessageBox.Show(String s = string.Format("Hello World"));
That is not the correct code, my only question is: Is something like that possible?

You can declare a string inside a call like that. However you can assign it.
string s = string.Empty;
MessageBox.Show(s = string.Format("Hello World"));
If you could declare strings inside a functioncall it wouldnt be visible elsewhere. So it woulndt really make any sense having that functionality in the language.

An alternative to Evelie's answer that lets you write it all in one line could be to define a helper method returning a string:
public static string ShowMsg(string msg) {
MessageBox.Show(msg);
return msg;
}
And your code would become:
string s = ShowMsg("Hello World");
or
string s = ShowMsg(string.Format("Now is {0}.", DateTime.Now));
And you could also perform the formatting inside your helper method:
public static string ShowMsg(string format, params object[] args) {
string mgs = string.Format(format, args);
MessageBox.Show(msg);
return msg;
}
And use it as:
string s = ShowMsg("Now is {0}.", DateTime.Now);

Related

Text to Speech C#

So I'm just a uni student who's enjoying programming (1st year) and I've decided to try out some new features.
I came across the speech synthesizer and its reallt interesting, but i have one problem.
Say if I said
Console.WriteLine("Hello");
Is there a way that I could get the program to say that without having to add
Console.WriteLine("Hello");
s.Speak("Hello");
?
Like I'm wondering if I am able to have my program speak whatever I type without adding extra code
Cheers
There is no way you could do that. But what you can try is creating a static method that takes a string value and prints "Hello" on to the console and use the TTS engine, like
static void PrintAndSpeak(string message)
{
Console.WriteLine(message);
s.Speak(message);
}
And then use the method inside the entry point:
PrintAndSpeak("Hello");
You could create a method that would take in your string. That method would print and read the message.
Example (pseudocode)
public void writeAndTalk(string message){
Console.WriteLine(message);
s.Speak(message);
}
And you then use the method wherever you like.
You could create a type to do this for you. Something like:
public class TextAndSpeech
{
private readonly WhateverSIs s;
public TextAndSpeech(WhateverSIs s)
{
this.s = s;
}
public Spurt(string message)
{
Console.WriteLine(message);
s.Speak(message);
}
}
I have no idea what type s is that you're using, so replace WhateverSIs with the actual type.
Using it would look something like:
var spurter = new TextAndSpeech(new WhateverSIs());
spurter.Spurt("Hello");
spurter.Spurt("Another thing.");

How to add to a class a string with two integers and show the sum

Greeting fellow programmers!
I am currently studying software development (I started not a month ago) and I have a problem that needs a solution. Underneath you can find the code and as you can see, the method WriteNumber needs help. I need to write the code in a way that when I run the program, on the console screen the following two lines will be shown:
Hello World!
81
The Main method code cannot be changed and also I cannot add more methods to the class Calculator so the code needs to be done only within the WriteNumbers method. I have tried a lot of things but I am still grasping how everything works so any help is welcome! Thank you in advance for your time.
Namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber()
{
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
Not to do your homework for you to just be copied/pasted, hopefully I can give you some hints...
Notice how the method is being invoked:
Calculator.WriteNumber(53 + 28)
The 53 + 28 part happens first, then the result of that operation is passed to the method. That result, naturally, is 81. What's important about that is its type, which is an integer.
So, reasonably, the method signature needs to accept an int as a parameter. This would be done very similarly to how the other method accepts a string as a parameter:
public static string WriteText(string input)
What, then, does that method need to do with that input? Well, it's only a single value, so there aren't any calculations to be performed on it. It would appear that the method simply needs to return the value as a string. (It's your homework so you tell me, is that correct?)
This can be done with exactly two things:
Calling .ToString() on the value
Using the return keyword to return the result of that operation
(Note: The .ToString() operation does something very intuitive on value types, such as int or double or bool. As you progress into using reference types, you're going to find that it does something very different. Any time you have a custom class on which you want to call .ToString(), you'll need to override the .ToString() method on that class first.)
Please read David's answer, it's important that you make the effort to understand why this works the way it does. That being said:
public static string WriteNumber(int number)
{
return number.ToString();
}
Thank you all for your valuable input but special thanks to David because he showed where I made my error. I forgot that the two numbers in the main function will be summed up FIRST and THEN forwarded to the method in the class Calculator. After that got cleared up, it was easy to understand what to do (basically adjust the type of the input parameter to int).
namespace CalculatorTest
{
class Calculator
{
public static string WriteText (string input)
{
return "" + input;
}
public static string WriteNumber(int sumOfNumbers)
{
return "" + sumOfNumbers;
}
}
class Program
{
static void Main(string[] args)
{
string s = Calculator.WriteText("Hello World!");
Console.WriteLine(s);
string n = Calculator.WriteNumber(53 + 28);
Console.WriteLine(n);
Console.Read();
}
}
}

it is possible to get stacktrace of methods calls inside call method?

I want to add more info to the logger at the call method level, and i need to know if exist possibility to get StackTrace of methods calls inside call method.
UPDATE: The purpose of this is to draw the flow of all methods called until the certain step inside call method.
EXAMPLE:
public class Type1
{
internal string method2_T1() {
return new Type2().method1_T2();
}
}
public class Type2
{
public string method1_T2()
{
return "Type2.method1_T2";
}
}
static void Main(string[] args)
{
string t = new Type1().method2_T1();
LogNow();
....
}
and the result to obtain, when I call LogNow(), are:
StackTrace of method2_T1()
...
Thanks
It's pretty easy:
var stackTrace = new StackTrace(true);
var traceToLog = stackTrace.ToString();
The true argument says to include the file info.
Todd Sprang's answer is good as the actual answer, but be aware that the stack trace will change in unpredictable ways when you move to a RELEASE build, or use async/await. Don't rely programatically on the answers because you may come unstuck when you put the code into production.
If you want to know the direct caller of a particular function, in a way Microsoft recommend, there's the useful trick using the [CallerMemberName], [CallerFilePath], and [CallerLineNumber] attributes. Mark up optional parameters like so;
public void LogWithCallerInfo(
string message,
[CallerMemberName] string memberName = "Caller",
[CallerFilePath] string sourceFilePath = "File",
[CallerLineNumber] int sourceLineNumber = 0)
{
WriteProgressMessage(..., memberName, sourceFilePath, sourceLineNumber);
}
and call like this;
LogWithCallerInfo("my message");
The three optional parameters will be replaced with the appropriate call info.

System.String[] argv conversion to string

Good Morning,
I have a problem with my WPF application, I need to use this method:
public static void LaunchTraining(System.String[] argv)
{
svm_train t = new svm_train();
t.run(argv);
}
The problem is that I do not have a stream from the Console (the input is a filename), but I need to declare the name of the file for this method, example:
string filename = "training.txt";
How can I convert my string into System.String[] argv?
There is no feasible way to do what you want.
The best solution would be to create an overload:
public static void LaunchTraining(String argv) {
// Handle String instead of String[]
}
Alternatively you could make an array:
LaunchTraining(new[]{"training.txt");
Maybe you just need the first item of the argv:
if(argv.Any()) t.run(argv[0]);
You can use this static method like below
LaunchTraining(new []{filename});

Parametrizing string in .NET C#

How to replace a method signature to accept parameterized strings without using param keywords. I have seen this functionality in Console.WriteLine().
e.g.
public void LogErrors(string message, params string[] parameters) { }
Scenario:
I have an error login function called
LogErrors(string message)
{
//some code to log errors
}
I am calling this function at different locations in the program in a way that the error messages are hardcoded. e.g.:
LogError("Line number " + lineNumber + " has some invalid text");
I am going to move these error messages to a resource file since I might change the language (localization) of the program later. In that case, how can I program to accept curly bracket bases parameterized strings? e.g.:
LogError("Line number {0} has some invalid text", lineNumber)
will be written as:
LogError(Resources.Error1000, lineNumber)
where Error1000 will be "Line number {0} has some invalid text"
Just call String.Format in your function:
string output = String.Format(message, parameters);
You probably want two methods:
public void LogErrors(string message, params string[] parameters)
{
LogErrors(string.Format(message, parameters));
}
public void LogErrors(string message)
{
// Use methods with *no* formatting
}
I wouldn't just use a single method with the params, as then it'll try to apply formatting even if you don't have any parameters, which can make things harder when you want to use "{" and "}" within a simple message without any parameters.
Basically use String.Format() method:
public void LogError(string format, params string[] errorMessages)
{
log.WriteError(String.Format(
CultureInfo.InvariantCulture,
format,
errorMessages));
}

Categories