2 params in C# not compiling - c#

I'm trying to do this:
public void CustomMethod(params int[] number,params string[] names)
{
...
}
If i delete one of them , there is no problems , any idea of why i can't do this?
I have tried putting a normal parametre in the middle of both.

Only the last parameter can have params. See the documentation.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
The reason is that allowing multiple params would give ambiguity. For example, what would this mean?
public void CustomMethod(params int[] foo, params int[] bar)
{
...
}
// ...
CustomMethod(1, 2);

This is simply not supported. The compiler can't know when one parameter list ends and the next begins.

As far as I know, you can only write one params parameter in the constructor which shall be the last parameter of the constructor.

The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
See Here : http://msdn.microsoft.com/en-us/library/w5zay9db(v=VS.71).aspx

Related

C# params argument selection when used twice

I'm curious why neither of the following DoInvoke methods can be called with only one params:
public class foo {
private void bar(params object[] args) {
DoInvoke(args);
}
//Error: There is no argument given that corresponds to the required formal parameter 'args' of 'foo.DoInvoke(Delegate, object[])'
private void DoInvoke(Delegate d, object[] args) {
d.DynamicInvoke(args);
}
//Error: Argument 1: cannot convert from 'object[]' to 'System.Delegate'
private void DoInvoke(Delegate d, params object[] args) {
d.DynamicInvoke(args);
}
}
I already found a way that doesn't abuse params. I'm curious why params are not expanded here.
I was able to do something similar in Lua, hence my attempt. I know Lua is far less strict, but I'm not sure which C# rule I'm breaking by doing this.
I'm curious why neither of the following DoInvoke methods can be called with only one params:
Short version: the first can't, because it has two non-optional parameters and because you're passing a value of the wrong type for the first non-optional parameter. The second can't, but only because the value you are trying to pass for the single non-optional parameter is of the wrong type; the second parameter is optional and so may be omitted as you've done.
You seem to be under the impression that in your method declaration private void bar(params object[] args), the presence of the params keyword makes the args variable somehow different from any other variable. It's not. The params keyword affects only the call site, allowing (but not requiring) the caller to specify the array elements of the args variable to be specified as if they were individual parameters, rather than creating the array explicitly.
But even when you call bar() that way, what happens is that an array object is created and passed to bar() as any other array would be passed. The variable args inside the bar() method is just an array. It doesn't get any special handling, and the compiler won't (for example) implicitly expand it to a parameter list for use in passing to some other method.
I'm not familiar with Lua, but this is somewhat in contrast to variadic functions in C/C++ where the language provides a way to propagate the variable parameter list to callees further down. In C#, the only way you can directly propagate a params parameter list is if the callee can accept the exact type of array as declared in the caller (which, due to array type variance in C#, does not always have to be the exact same type, but is still limited).
If you're curious, the relevant C# language specification addresses this in a variety of places, but primarily in "7.5.1.1 Corresponding parameters". This reads (from the C# 5 specification…there is a draft C# 6 specification, but the C# 5 is basically the same and it's what I have a copy of):
For each argument in an argument list there has to be a corresponding parameter in the function member or delegate being invoked.
It goes on to describe what "parameter list" is used to validate the argument list, but in your simple example, overload resolution has already occurred at the point this rule is being applied, and so there's only one parameter list to worry about:
• For all other function members and delegates there is only a single parameter list, which is the one used.
It goes on to say:
The corresponding parameters for function member arguments are established as follows:
• Arguments in the argument-list of instance constructors, methods, indexers and delegates:
o A positional argument where a fixed parameter occurs at the same position in the parameter list corresponds to that parameter. [emphasis mine]
o A positional argument of a function member with a parameter array invoked in its normal form corresponds to the parameter array, which must occur at the same position in the parameter list.
o A positional argument of a function member with a parameter array invoked in its expanded form, where no fixed parameter occurs at the same position in the parameter list, corresponds to an element in the parameter array.
o A named argument corresponds to the parameter of the same name in the parameter list.
o For indexers, when invoking the set accessor, the expression specified as the right operand of the assignment operator corresponds to the implicit value parameter of the set accessor declaration.
In other words, if you don't provide a parameter name in your argument list, arguments correspond to method parameters by position. And the parameter in the first position of both your called methods has the type Delegate.
When you try to call the first method, that method has zero optional parameters, but you haven't provided a second parameter. So you get an error telling you that your argument list, consisting of just a single argument (which by the above corresponds to the Delegate d parameter), does not include a second argument that would correspond to the object[] args parameter in the called method.
Even if you had provided a second argument, you would have run into the same error you get trying to call your second method example. I.e. while the params object[] args parameter is optional (the compiler will provide an empty array for the call), and so you can get away with providing just one argument in your call to the method, that one argument has the wrong type. Its positional correspondence is to the Delegate d parameter, but you are trying to pass a value of type object[]. There's no conversion from object[] to Delegate, so the call fails.
So, what's that all mean for real code? Well, that depends on what you are trying to do. What did you expect to happen when you tried to pass your args variable to a void DoInvoke(Delegate d, params object[] args) method?
One obvious possibility is that the args array contains as its first element a Delegate object, and the remainder of the array are the arguments to pass. In that case, you could do something like this:
private void bar(params object[] args) {
DoInvoke((Delegate)args[0], args.Skip(1).ToArray());
}
That should be syntactically valid with either of the DoInvoke() methods you've shown. Of course, whether that's really what you want is unclear, since I don't know what the call was expected to do.

Pass the collection result of a method as params argument

I have a method that takes params and I want to provide those params with another method. Example:
public void Process(params string[] words)
{
// do some stuff
}
public IEnumerable<string> GetWords()
{
yield return "test";
}
Process(GetWords()); // Error collection of strings must be passed individually
However this is not allowed because the result is considered a single parameter of type IEnumerable instead of a set of parameters type string. I've tried using ToArray and ToList, same problem. Is there a way to use the result of a method as params argument?
Edit: The problem occurs when you pass another argument first. The problem is I need to keep access to the first parameter but not the others. That can be done by letting the method create all parameters, calling it separately and keeping a reference to the first element.
I think you want
Process(GetWords().ToArray());

How i can pass two params Expression inside my method

I am working on an asp.net mvc web application, and i need to pass two params expression as follow:-
public RackJoin AllFindDetails(int id, params Expression<Func<Server, object>>[] includeProperties,params Expression<Func<Resource, object>>[] includeProperties2)
{
but the above will raise the following error:-
A parameter array must be the last parameter in a formal parameter list
You need to find a different solution. Since params just takes every argument given it and stuffs them into an array, two instances of it on the same function don't make sense.
MSDN formalizes this:
No additional parameters are permitted after the params keyword in a
method declaration, and only one params keyword is permitted in a
method declaration.
The specification is slightly less specific (Section 1.6.6.1):
Only the last parameter of a method can be a parameter array, and the type of a parameter array must be a single-dimensional array type.
But only allowing the last parameter to be params implies there can only be one, since a second one by definition could not be the last one as well.

Named arguments call in C# with variable parameter number

Suppose I have the following C# function:
void Foo(int bar, params string[] parpar) { }
I want to call this function using named arguments:
Foo(bar: 5, parpar: "a", "b", "c");
The compiler gives error message: “Named arguments cannot precede positional” since I have no name before “b” and “c”.
Is there any way to use named arguments without manually representing params as an array?
No, there is no syntactic sugar to make variable arguments named except explicitly specifying array.
Note that params arguments would need to be individually named if such syntax would be allowed (to see where positioned argument ends), but there is only one name.
Adding this in case someone lands here from google like I did. You will also receive this error when you have not explicitly named all your parameters and all your explictly named parameters are not at the end.
void Foo( int parameterOne, int parameterTwo, int parameterThree) {};
// throws Named Arguments cannot precede positional
Foo(parameterOne: 1, parameterTwo:2, 3);
//This is okay
Foo(1, parameterTwo:2, parameterThree:3);

function overload

Can I have two same function name with same parameters but different meaning.
For example:
public void test(string name)
public void test(string age)
Thank you.
No, you can't. The signature is not different - it doesn't matter what the parameter names are.
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
http://msdn.microsoft.com/en-us/library/ms173114.aspx
Like a few other answers have stated, consider the type of data you're taking in. Name is indeed a typical string, but does age have to be? If you allow it to be a - for example - int then you can overload your method as you wish.
No, you cannot overload on a return type or a parameter name. Unlike some other languages (most notably, Objective C1) parameter name is not part of the signature of your function.
The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
1 even there it's not exactly the parameter name that becomes part of the selector.
You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.
No.
Signatures and Overloading
If you need a method with different meaning why won't you create a method with a different name? It would be confusing to use the same method name for different things on the same object.
You could mix together these methods using optional parameters and default values:
public void test(string name = null, string age = null)
{
if (name != null)
{
// Do something
}
else if (age != null)
{
// Do something else
}
}
And you could call this method like that:
test(name: "John");
test(age: "30");
Not very clean, but still useable.
No - the compiler throws an error because compiler use parameters to detemine which method to call, not the return type.
NO.
An OVERLOADED FUNCTION must have different SIGNATURE.
i.e.- arguments should be different, either in terms of number of arguments or order of different datatypes arguments.

Categories