Named arguments call in C# with variable parameter number - c#

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);

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.

c# Is there a parameters construct similar to multiple variable declaration?

When declaring variables of the same type, we normally do this:
int a,b,c,d;
Is there a construct to do something similar with function parameters?
This function would take 3 integers:
void foo(int a,b,c)
{
}
No, there is no such construct for declaring method arguments. You must declare your parameters one by one.
The closest thing that lets your method receive multiple parameters declared as a single array parameter is params:
void Foo(params int[] a) {
...
}
This method can be called as follows:
Foo(a, b, c, d);
The caller can pass any number of separate parameters, including zero. Your method would receive all of them in a single array.
No, there's not. This is the documentation about arguments:
https://msdn.microsoft.com/en-us/library/aa691335(v=vs.71).aspx

2 params in C# not compiling

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

C# : overloading constructors with optional parameters & named arguments?

This isn't a question on proper coding practice, I'm just working through the semantics.
lets say I have the following constructors...
public FooClass(string name = "theFoo")
{ fooName = name; }
public FooClass(string name, int num = 7, bool boo = true) : this(name)
{ fooNum = num; fooBool = boo; }
is it possible to use named arguments thusly...?
FooClass foo1 = new FooClass(num:1);
// where I'm only passing one named argument, relying on the optionals to take care of the rest
or call the constructor FooClass(string, int, bool) with no arguments? as in...
FooClass foo2 = new FooClass();
Use of named and optional arguments affects overload resolution in the following ways:
A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.
If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.
http://msdn.microsoft.com/en-us/library/dd264739.aspx
Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported.
Also,
A named argument can follow positional arguments, as shown here.
CalculateBMI(123, height: 64);
However, a positional argument cannot follow a named argument. The following statement causes a compiler error.
//CalculateBMI(weight: 123, 64);

C# method call with parameter name and colon

I've begun to notice at times when I'm making method calls in C# that the names of the parameters for the method I'm calling will show up in the intellisense list appended with a colon, and that I can then format the method call thusly:
MethodCall(parameter1:value1, parameter2:value2);
Is this a new language feature? It reminds me of the way you can call stored procedures in SQL and specify parameter names like so:
spDoSomeStuff #param1 = 1, #param2 = 'other param'
Is this a similar feature? If so, to what end? If not, what is it and what is it to be used for.
It's a new feature. See here: http://msdn.microsoft.com/en-us/library/dd264739.aspx
Named parameters are standard in ObjectiveC for instance. It takes some time to get used to them but they are a good thing. Only from looking you can tell what a parameter is meant for.
It is worth mentioning, unlike optional parameters, you can skip certain arguments and pass only the parameters you are interested in.
public void Example(int required, string StrVal = "default", int IntVal = 0)
{
// ...
}
public void Test()
{
// This gives compiler error
// Example(1, 10);
// This works
Example(1, IntVal:10);
}
Named parameters allow you explicitly set the value of arguments in a custom order independent of the signature. Method signatures are defined by the argument types, ie, Foo( int i, bool b ), which will only accept arguments of type int and bool in that order. Named arguments allow you to pass b first and i second.
Scott Gu has introduced this new feature in his blog:
Optional Parameters and Named Arguments in C# 4
It's the Named and Optional Parameters that came in with C# 4.

Categories