This is due to the fact that unlike Console.Write
, Interaction.Msgbox
does not know anything about string.Format
: It just displays the string "as is".
Since C# version 6, there is a comfortable way:
Interaction.MsgBox($"Result:\n {tal1 * tal2}");
The '$' is telling the compiler to treat {tal1 * tal2}
as an expression and insert the result into the string. More details about this so-called string interpolation:
With string interpolation, expressions within curly braces {}
can
also be evaluated. The result will be inserted at the corresponding
location within the string. For example, to calculate the maximum of
foo
and bar
and insert it, use Math.Max
within the curly
braces:
Console.WriteLine($"And the greater one is: {
Math.Max(foo, bar) }");
Output:
And the greater one is: 42
Note: Any leading or trailing whitespace (including space, tab and CRLF/newline) between the curly brace and the expression is completely ignored and not included in the output
For all C# versions (especially the ones before C#6) you can do the following:
Instead of having to invoke string.Format
every time, you can create a function like
public Microsoft.VisualBasic.MsgBoxResult MsgBox(string msg, params object[] p)
{
var fmt = string.Format(msg, p);
var msgStyle = Microsoft.VisualBasic.MsgBoxStyle.OkOnly;
return Interaction.MsgBox(fmt, msgStyle, "Information");
}
This can be used as follows:
var tal1=1; var tal2=2;
MsgBox("Hello!\nResult:{0}\n", (tal1 + tal2));
Note: This solution supports not only {0}
, but also {1}, {2}, ...
because I have used a params array. Hence, the following is working too:
MsgBox("Calculation: {0} + {1} = {2}", tal1, tal2, (tal1+tal2));
which outputs Calculation: 1 + 2 = 3
.
You can read here (at Microsoft) more about the Interaction.MsgBox
method, how to change the style of the messagebox (e.g. how to display Yes/No/Cancel buttons and about the MsgBoxResult
values being returned) so you can tailor it to your needs.
This is the complete program, you can run it in LinqPad or Visual Studio:
static void Main(string[] args)
{
var tal1=1; var tal2=2;
MsgBox("Hello!\nResult:{0}\n", (tal1 + tal2));
MsgBox("Calculation: {0} + {1} = {2}", tal1, tal2, (tal1+tal2));
}
public static MsgBoxResult MsgBox(string msg, params object[] p)
{
var fmt=string.Format(msg, p);
var msgStyle= Microsoft.VisualBasic.MsgBoxStyle.OkOnly;
return Interaction.MsgBox(fmt, msgStyle, "Information");
}
Don't forget to add a reference to Microsoft.VisualBasic.dll
, using the namespace Microsoft.VisualBasic
in order to run this example.
If you're using LinqPad, right-click, choose "Query properties..." then add the dll in "Additional references" and the namespace in "Additional Namespace imports".