Arunald Arunald - 13 days ago 6
C# Question

How to Pass this parameter?

I have trying to mirror the output screen to .txt file.By my below code i can able to mirror the output screen to text file. When executing the

obj.OutputFile("First text");
there is no problem But some times i need print like
obj.OutputFile("Second text {0}",text);


I got the exception during the second line execution


No overload for method 'OutputFile' takes 2 arguments test document


How do i clear my exception?

I want to my code which is to be accept different number of arguments passing.

My Code

class Program
{

static void Main(string[] args)
{
string text = "Sample";
Program obj = new Program();
obj.OutputFile("First text");
obj.OutputFile("Second text {0}",text);
Console.ReadKey();
}
public void OutputFile(string text)
{

string path = "Example.txt";

if (!File.Exists(path))
{
using (TextWriter tw = new StreamWriter(path))
{
tw.WriteLine(text);
Console.WriteLine(text);
}
}
else if (File.Exists(path))
{
using (TextWriter tw = new StreamWriter(path,true))
{
tw.WriteLine(text);
Console.WriteLine(text);
}
}
}
}


I am totally new to this c#. So i hope your answer would be simple.

Answer

Your call for OutputFile doesn't seem correct. You have obj.OutputFile("Second text {0}",text); while the method signature is public void OutputFile(string text), which means it requires one parameter.

All you have to do is to change your call to:

obj.OutputFile(string.Format("Second text {0}", text));

And if you are using C# 6 you can make it even better:

obj.OutputFile($"Second text {text}");