Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in multiple parameters as string array

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...?

like image 599
fifamaniac04 Avatar asked Mar 01 '26 14:03

fifamaniac04


1 Answers

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());
like image 180
benPearce Avatar answered Mar 04 '26 04:03

benPearce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!