-2

I am creating a program that sends an email with some data the program collected from the user beforehand.

Currently, my problem is that when i use:

string subject = "test {0}", test2;

The email I receive is this output:

test {0}

and not the expected output of:

"test test2".

Is there something I am missing?

I just tested something else out, by removing the text and only using the variable as a subject, worked fine. But why isnt the text/string + variable working?

Vs says that the variable I am adding, test2, is already defined.

Full code:

string test2 = "test";
string subject = "test {0}", test2;
string body = "test1";
Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
OG-TRTA
  • 1
  • 2

1 Answers1

2

It's because you need to wrap the formatted string in the String.Format() or a Console.WriteLine();

It should be

string test2 = "test";
string subject = String.Format("test {0}", test2);
string body = "test1";

Without the String.Format C# just thinks that you're defining 2 separate string variables. It creates 1 variable named subject which is equal to "test {0}" and another variable named test2 which you already defined in the line before which is why it's complaining. It thinks you're trying to say

string test2 = "test";
string subject = "test {0}";
string test2;
string body = "test1";

Read the documentation for composite formatting. https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting

Gloria
  • 56
  • 4