How to create a method with an undefined number of parameters en C #

This is my code:

private static string AddURISlash(string remotePath) { if (remotePath.LastIndexOf("/") != remotePath.Length - 1) { remotePath += "/"; } return remotePath; } 

But I need something like

 AddURISlash("http://foo", "bar", "baz/", "qux", "etc/"); 

If I remember correctly, string.format is something like this ...

 String.Format("{0}.{1}.{2}.{3} at {4}", 255, 255, 255, 0, "4 pm"); 

Is there anything in C # that allows me to do this?

I know what I could do

 private static string AddURISlash(string[] remotePath) 

but this is not an idea.

If this is something in some frameworks, it is possible to do, but in others not to indicate how to resolve it.

Thanks in advance

+4
source share
4 answers

You can use parameters that allow you to specify any number of arguments

 private static string AddURISlash(params string[] remotePaths) { foreach (string path in remotePaths) { //do something with path } } 

Note that params will affect the performance of your code, so use it sparingly.

+5
source

I think you want an array of parameters :

 private static string CreateUriFromSegments(params string[] segments) 

Then you implement it, knowing that remotePath is just an array, but you can call it with:

 string x = CreateUriFromSegments("http://foo.bar", "x", "y/", "z"); 

(As noted in the comments, an array of parameters can only be displayed as the last parameter in the declaration.)

+6
source

Try

 private static string AddURISlash(params string[] remotePath) 

This will allow you to pass string[] as several separate parameters.

+3
source

This may be what you are looking for (note the params ):

 private static string AddURISlash(params string[] remotePath) { // ... } 
+3
source

Source: https://habr.com/ru/post/1398874/


All Articles