Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named parameters with params

Tags:

I have a method for getting values from database.

 public virtual List<TEntity> GetValues(            int? parameter1 = null,            int? parameter2 = null,            int? parameter3 = null,            params Expression<Func<TEntity, object>>[] include)         {             //...         }  

How can I call this function with named parameter to not write all parameters before include? I want to do something like this

var userInfo1 = Unit.UserSrvc.GetValues(include: p => p.Membership, p => p.User); 

But this doesn't seem working? How can I use named parameter with params?

like image 852
Chuck Norris Avatar asked Mar 26 '12 12:03

Chuck Norris


People also ask

What is named parameters in C#?

Named parameters provides us the relaxation to remember or to look up the order of parameters in the parameter lists of called methods. The parameter for each argument can be specified by parameter name. Using named parameters in C#, we can put any parameter in any sequence as long as the name is there.

Can positional parameters and named parameters be intermingled R?

Mixing Named and Positional ParametersIt is possible to use named parameters and positional parameters in the same call. Named parameters must be used after positional parameters.

How do you add optional parameters?

In the following example, I define the second parameter (secondNumber) as optional; Compiler will consider “0” as default value. Optional attribute always need to be defined in the end of the parameters list. One more ways we can implement optional parameters is using method overloading.

Does JavaScript have named parameters?

JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.


2 Answers

I think the only way is something like:

GetValues(include:    new Expression<Func<TEntity, object>>[] { p => p.Membership, p => p.User }) 

Which is not that great. It would be probably best if you added an overload for that:

public List<Entity> GetValues(params Expression<Func<Entity, object>>[] include) {     return GetValues(null, null, null, include); } 

Then you call your method just like

GetValues(p => p.Membership, p => p.User) 
like image 64
svick Avatar answered Oct 11 '22 23:10

svick


A params argument works like an array, try this syntax:

var userInfo1 = Unit.UserSrvc.GetValues(include: new Expression<Func<TEntity, object>>[] { p => p.Membership, p => p.User }); 

(Might need some adapting due to the generic parameter, but I think you get the gist of it)

like image 40
madd0 Avatar answered Oct 11 '22 23:10

madd0