nyxthulhu
nyxthulhu

Reputation: 9752

Accepting a non fixed length group of parameters in a function

So what I'm trying to do is build a logging function, I'm hoping to get it taking the format

public static void AddToLog(Guid someID, LogArea myLogger, string message, object object1, object object2... ... ...);

The second to last parameter I'd like to accept a string which is in the format of something akin to string.format and the last X parameters would be the objects to replace with the string format with.

I'm having a hard time because I can't remember what the programming concept is called to search for to find examples of this in C#. I also realise there's fantastic logging packages out there - I just need this to do something special that's why I'm re-inventing the wheel :D

Could any suggest how to tell C# not to expect a fixed length of parameters? (and for bonus points if anyone knows how to best document this in the /// notation I'd really appreciate it).

Upvotes: 0

Views: 145

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460018

You are looking for the params[].

public static void AddToLog(Guid someID, LogArea myLogger, string message, params object[] list)
{
    // you can use it like an array
    Console.WriteLine("Guid:{0} Message:{1} Objects:{2}"
        , someID, message, string.Join(",", list));
}

Upvotes: 3

ChrisO
ChrisO

Reputation: 5465

I believe the keyword you're looking for is params

public static void AddToLog(Guid someID, LogArea myLogger, string message, params object[] objects)

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27584

Use params:

public static void AddToLog(
    Guid someID, LogArea myLogger, string message, params object[] parameters)
{
    foreach(object p in parameters)
    {
        Console.WriteLine(p);
    }
}

Upvotes: 2

Related Questions