wscales10
wscales10

Reputation: 33

Is it possible to pass the elements of a list as arguments of one function call in C#?

I am writing a bot designed to interact with an online game. I am using a function called "Send" which is defined like so:

public void Send(string type, params object[] parameters);

"Send" is a function which can have a variable number of arguments, thanks to the params keyword. If I am storing these arguments in a List<object>, can I pass this list of arguments to the function without having to write different code for each possible number of arguments?

I know that if that params keyword wasn't there I could just pass the whole list as one argument using List<T>.ToArray(), but the Send function is defined in a preprepared library which I can't alter.

Upvotes: 1

Views: 1822

Answers (2)

eocron
eocron

Reputation: 7526

Small explanation:

var myList = new List<object>() { 1, "foo", "bar"};

Send(type, myList.ToArray());         //this will invoke: void Send(string, object, object, object);
Send(type, (object)myList.ToArray()); //this will invoke: void Send(string, object);
Send(type, myList);                   //this will invoke: void Send(string, object);

So if you want your list to be considered as params - you can invoke ToArray(), if you want it to be considered as single parameter - just cast it to object.

Upvotes: 2

Larz
Larz

Reputation: 51

but the Send function is defined in a preprepared library which I can't alter.

You could define an extension method,

// Where Lib is the type that contains the Send method.
public static class MyExtensions
{
    public static void Send(this Lib lib, string type, int obj)
    {
        lib.Send(type, obj);
    }

    public static void Send(this Lib lib, string type, List<object> objs)
    {
        lib.Send(type, objs.ToArray());
    }

    // Other overloads
}

Then you use it just like it was built into the library to being with,

var lib = new Lib();
lib.Send(type, 1) // Call Send(this Lib lib, string type, int obj)

Upvotes: 0

Related Questions