Unnikrishnan Unnikrishnan - 1 month ago 11
C# Question

Is there any difference in Console.WriteLine("{0}, var); and MessageBox.Show("{0},var)

Is there any error in the following statement?

var str = "Hello how are you.";
MessageBox.Show("{0}",str);


My problem was in the following code where I was not getting it correctly. The code below is part of learning process. In the MessageBox the 'designation' variable is not coming as I stated above!

abstract class Employee //Abstract class
{
public virtual void WhichCoEmployee()
{
MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation); //My problem was in this line.
//designation varaiable was not received in
//placeholder {0} for display in MessageBox.Show.
}
public void Designation(string desig)
{
designation = desig;
}
public string designation { get; set; }
}

class CEO : Employee //Inheritance
{
public void Name()
{
MessageBox.Show("My name is Unnikrishnan C");
}
}

private void button2_Click(object sender, EventArgs e)
{
CEO ceo = new CEO(); //Initializing the CEO class.
ceo.Name();
ceo.Designation("CEO");
ceo.WhichCoEmployee();
}


Subsequenly I have rectified the MessageBox.Show problem by changing the
the Message Box code.

MessageBox.Show("I am employed in XYZ Corporation as its " + designation);


That worked fine.

Answer

EDIT:

Simply change

MessageBox.Show("I am employed in XYZ Corporation as its {0}", designation);

to

MessageBox.Show("I am employed in XYZ Corporation as its " + designation);

BTW, you need to call this method somewhere for the code to run!


No. Your two lines seems to be perfectly correct according to the syntax.

But it seems that what you are trying to achieve is something different than what you have done.. Here's the thing: You just called this overloaded version of Show method of MessageBox class, which accepts two strings.

public static DialogResult Show(string text, string caption);

Hence in your case, a message box with "{0}" text and "Hello how are you." caption will be shown.

However, Console.WriteLine("{0}", var); is completely different. It is used to print output to the console. It also has many overloaded varieties, and in this case, it will replace {0} with the value of var variable. Hence, "Hello how are you." will be outputted to the Console.

Comments