3

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

benPearce
  • 37,735
  • 14
  • 62
  • 96
fifamaniac04
  • 2,343
  • 12
  • 49
  • 72
  • Sounds like you might want the `params` keyword. http://stackoverflow.com/q/7580277/97382 – Craig W. Jun 10 '15 at 22:55
  • nope, it gives an error saying "Can't convert string[] to string" ... probably because the `params` works on individual objects, not collections/lists/arrays – fifamaniac04 Jun 10 '15 at 23:00
  • You can't just slap `params` on your existing code without making a few changes. Your description of what you're trying to accomplish is pretty vague so it's tough to be any more specific than that, but bottom line is that if you want to pass a variable number of arguments (of the same type) to a method the `params` is the way to go. It would also be helpful if you explained what your `this does not work` comment means. Just a quick glance seems like it should be fine. – Craig W. Jun 10 '15 at 23:04
  • @CraigW. What I'm trying to get at is how to call `AddLogEntry()` inside `LogMethodStart()`. notice that essentially I'm trying to prepend the array that will be passed into `AddLogEntry()`... I am not passing in arguments of the same type, one is an array, one is an object of the type of the array... run my code and see you get the compile error I mention – fifamaniac04 Jun 10 '15 at 23:13
  • @CraigW. `params` don't help to remove null checks as one can still use original syntax to pass `null` ( `Foo((string[])null)` ) – Alexei Levenkov Jun 10 '15 at 23:35

1 Answers1

9

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());
benPearce
  • 37,735
  • 14
  • 62
  • 96