Is it possible in C# to accept a params argument, then pass it as params list to another function? As it stands, the function below will pass args as a single argument that is an array of type object, if I'm not mistaken. The goal here is self evident.
//ScriptEngine
public object[] Call(string fnName, params object[] args)
{
try{
return lua.GetFunction(fnName).Call(args);
}
catch (Exception ex)
{
Util.Log(LogManager.LogLevel.Error, "Call to Lua failed: "+ex.Message);
}
return null;
}
The lua.GetFunction(fnName).Call(args); is a call to outside of my code, it accepts param object[].
If the signature of the Call method you're calling accepts a params object[] args then you are mistaken. It doesn't consider args a single object of thpe object, to be wrapped in another array. It considers it the entire argument list, which is what you want. It'll work just fine exactly as it stands.
Yes, it is possible.In your case args actualy an array of objects.Your Call method should take params object[] or just an array of objects as parameter.
You don't need to pass more than one argument to params.You can pass an array directly.For example this is completely valid:
public void SomeMethod(params int[] args) { ... }
SomeMethod(new [] { 1, 2, 3 });
It is possible to pass the array to another function:
void Main()
{
int[] input = new int[] {1,2,3};
first(input); //Prints 3
}
public void first(params int[] args)
{
second(args);
}
public void second(params int[] args)
{
Console.WriteLine(args.Length);
}
Related
Consider this code sample from a WinForms app:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";
DoSomething(parms);
}
public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}
It works as expected, when you click button1 it prints "Something good happened" to the console.
Now consider this code sample, which is the same except that it invokes DoSomething using reflection:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object[] parms = new object[1];
parms[0] = "foo";
System.Reflection.MethodInfo mi = typeof(Form1).GetMethod("DoSomething");
mi.Invoke(null, parms);
}
public static string DoSomething(object[] parms)
{
Console.WriteLine("Something good happened");
return null;
}
}
It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)
parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array. So why is invoke pulling the first object out of the array and trying to pass that instead?
Or is something else going on that I'm not understanding?
MethodInfo.Invoke is expecting an object array, where each object in the object array corresponds to an argument to the method. The first argument in the object array is the first argument, the second object in the array the second method, etc.
Since you want the first argument to your method to be an object[], you need to ensure that the first object in the object array you pass to MethodInfo.Invoke is an object array that represents the array that DoSomething should use.
object[] parms = new object[1];
parms[0] = "foo";
with:
public static string DoSomething(object[] parms)
that's the problem; the first parameter is not a string - it is an object[]. The object[] that you pass to Invoke represents each parameter in turn, so an object[] of length 1 with a string would match static string DoSomething(string s), but does not match your method. Either change the signature, or wrap the value. Frankly, I suggest changing the signature is the better idea here, but:
parms[0] = new object[] { "foo" };
would also work
MethodInfo.Invoke expects an array of objects as parameter to pass multiple arguments to the functions, each object in the array will be a different parameter.
As your function also expects an object array you are passing as argument not an object array but an string.
You must wrap that array into another array, in this way the Invoke will unwrap the first array and use the inner array as the first parameter for the call.
mi.Invoke(null, new object[]{ parms });
parms is clearly an object array, and DoSomething's method signature is clearly expecting an object array.
Yes it is expecting an object array. But when you pass this:
object[] parms = new object[1];
You are saying these are the arguments for DoSomething so parms[0] is the first argument to DoSomething and if there were more items in parms then parms[1] will be the 2nd argument and so on.
Clearly the first argument for DoSomething is not a string (parms[0]) so you get this error:
It throws an System.ArgumentException on the line mi.Invoke(null, parms) (Object of type 'System.String' cannot be converted to type 'System.Object[]'.)
In order to change a control by another thread, I need to invoke a delegate to change the control However, it is throwing a TargetParameterCountException:
private void MethodParamIsObjectArray(object[] o) {}
private void MethodParamIsIntArray(int[] o) {}
private void button1_Click(object sender, EventArgs e)
{
// This will throw a System.Reflection.TargetParameterCountException exception
Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { });
// It works
Invoke(new Action<int[]>(MethodParamIsIntArray), new int[] { });
}
Why does invoking with MethodParamIsObjectArray throw an exception?
This is due to the fact that the Invoke method has a signature of:
object Invoke(Delegate method, params object[] args)
The params keyword in front of the args parameter indicates that this method can take a variable number of objects as parameters. When you supply an array of objects, it is functionally equivalent to passing multiple comma-separated objects. The following two lines are functionally equivalent:
Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { 3, "test" });
Invoke(new Action<object[]>(MethodParamIsObjectArray), 3, "test");
The proper way to pass an object array into Invoke would be to cast the array to type Object:
Invoke(new Action<object[]>(MethodParamIsObjectArray), (object)new object[] { 3, "test" });
Invoke expects an array of objects containing the parameter values.
In the first call, you aren't providing any values. You need one value, which confusingly needs to be an object array itself.
new object[] { new object[] { } }
In the second case, you need an array of objects containing an array of integers.
new object[] { new int[] { } }
public class bar:foo
{
public bar(int something, params object[] parameters)
:base(something, parameters) //foo will receive {int, object[]}, not what i want
{
}
}
public class foo
{
public foo(params object[] parameters)
{
}
}
so basically i would like to append one more object infront of the params array which i pass into the base class. Lets say I call bar(1, 2, 3, 4, 5) i want foo to receive {1, 2, 3, 4, 5} as params instead of {1, {2, 3, 4, 5}} which is what the code above is giving me.
The solution is to create a new array that contains the first element + the elements from the original array, and pass the new array to the other method.
You can do that by creating a new array that holds the first parameter, and using Concat to create a collection containing this parameter and the original array, and then turning that collection back into an array.
This expression would do it:
new object[] { something }.Concat(parameters).ToArray()
Thus your constructor definition would look like this:
public bar(int something, params object[] parameters)
:base(new object[] { something }.Concat(parameters).ToArray())
{
}
Old school:
Create array [N + 1]
Copy the first parameter
Copy/Append the params array, after that.
Sometimes you don't need LINQ, where the size of the arrays is known in this case.
public static T[] Append<T>(this T first, params T[] items)
{
T[] result = new T[items.Length + 1];
result[0] = first;
items.CopyTo(result, 1);
return result;
}
(For very old school use Object instead of T)
I like an extension; bit of both answers so far:
public static class ObjectExtensions
{
public static object[] PrependToParamArray(this object me, params object[] args)
{
return new[] {me}.Concat(args).ToArray();
}
}
Usually arrays are frowned upon. A better solution would use a LinkedList which provides ways for adding front
Édit
If you need to keep the variable parameters then you can use the .Union.ToArray() method available on c# arrays
I have a class which contains an empty constructor and one that accepts an array of objects as its only parameter. Something like...
public myClass(){ return; }
public myClass(object[] aObj){ return; }
This is the CreateInstance() method call that I use
object[] objectArray = new object[5];
// Populate objectArray variable
Activator.CreateInstance(typeof(myClass), objectArray);
it throws System.MissingMethodException with an added message that reads
"Constructor on type 'myClass' not found"
The bit of research that I have done has always shown the method as being called
Activator.CreateInstance(typeof(myClass), arg1, arg2);
Where arg1 and arg2 are types (string, int, bool) and not generic objects.
How would I call this method with only the array of objects as its parameter list?
Note: I have tried adding another variable to the method signature. Something like...
public myClass(object[] aObj, bool notUsed){ return; }
and with this the code executed fine.
I have also seen methods using reflection which were appropriate but I am particularly interested in this specific case. Why is this exception raised if the method signature does in fact match the passed parameters?
Cast it to object:
Activator.CreateInstance(yourType, (object) yourArray);
Let's say you have constructor:
class YourType {
public YourType(int[] numbers) {
...
}
}
I believe you would activate like so by nesting your array, the intended parameter, as a item of the params array:
int[] yourArray = new int[] { 1, 2, 4 };
Activator.CreateInstance(typeof(YourType ), new object[] { yourArray });
In C# you can do this:
foo = string.Format("{0} {1} {2} {3} ...", "aa", "bb", "cc" ...);
This method Format() accepts infinite parameters, being the first one how the string should be formatted and the rest are values to be put in the string.
Today I've come to a situation where I had to get a set of strings and test them, then I remembered this language functionality, but I had no clue. After a few unsuccessful web searches, I've realised it would be more prudent to just get an array, which didn't make me quite satisfied.
Q: How do I make a function that accepts infinite parameters? And how do I use it ?
With the params keyword.
Here is an example:
public int SumThemAll(params int[] numbers)
{
return numbers.Sum();
}
public void SumThemAllAndPrintInString(string s, params int[] numbers)
{
Console.WriteLine(string.Format(s, SumThemAll(numbers)));
}
public void MyFunction()
{
int result = SumThemAll(2, 3, 4, 42);
SumThemAllAndPrintInString("The result is: {0}", 1, 2, 3);
}
The code shows various things. First of all the argument with the params keyword must always be last (and there can be only one per function). Furthermore, you can call a function that takes a params argument in two ways. The first way is illustrated in the first line of MyFunction where each number is added as a single argument. However, it can also be called with an array as is illustrated in SumThemAllAndPrintInString which calls SumThemAll with the int[] called numbers.
Use the params keyword. Usage:
public void DoSomething(int someValue, params string[] values)
{
foreach (string value in values)
Console.WriteLine(value);
}
The parameter that uses the params keyword always comes at the end.
A few notes.
Params needs to be marked on an array type, like string[] or object[].
The parameter marked w/ params has to be the last argument of your method. Foo(string input1, object[] items) for example.
use the params keyword. For example
static void Main(params string[] args)
{
foreach (string arg in args)
{
Console.WriteLine(arg);
}
}
You can achieve this by using the params keyword.
Little example:
public void AddItems(params string[] items)
{
foreach (string item in items)
{
// Do Your Magic
}
}
public static void TestStrings(params string[] stringsList)
{
foreach (string s in stringsList){ }
// your logic here
}
public string Format(params string[] value)
{
// implementation
}
The params keyword is used
function void MyFunction(string format, params object[] parameters) {
}
Instad of object[] you can use any type your like. The params argument always has to be the last in the line.