Passing in multiple parameters as string array

6.3k views Asked by At

I have a function that accepts a string array as a parameter

public static void LogMethodStart(string[] parameters)
{
    AddLogEntry("Starting Method", parameters); //this does not work
}

public static void AddLogEntry(string[] parameters)
{ 
    using(StreamWriter sw = new StreamWriter(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), FileName), true))
    {
        foreach (string p in parameters)
        {
            stream.WriteLine(p.ToString() + DateTime.Now.ToString());
        }
    }
}

Is there a way to pass an element to be included as an Array without having to do some Array.resize() operation and check for null etc...?

1

There are 1 answers

1
benPearce On

Change your method signature to this:

public static void LogMethodStart(params string[] parameters)
{
    AddLogEntry("Starting Method", parameters); //this does not work
}

Then you can call it in a couple of ways:

LogMethodStart("string1","string2");
LogMethodStart(new string[] {"string1","string2"});

Both of these will look the same inside the method.

EDIT:

Modify your LogMethodStart body:

var newParams = new List<string>(parameters);
newParams.Insert(0,"Starting Method");
AddLogEntry(newParams.ToArray());