Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a method with unspecified amount of params en C#

Tags:

c#

parameters

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 recall correctly, string.format is somehow like that...

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

Is there something in C# that allows me to do so?

I know I could do

private static string AddURISlash(string[] remotePath)

but that's not the idea.

If this is something in some framework can be done and in others not please specify and how to resolve it.

Thanks in advance

like image 694
apacay Avatar asked Dec 03 '22 04:12

apacay


2 Answers

I think you want a parameter array:

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 comments, a parameter array can only appear as the last parameter in a declaration.)

like image 181
Jon Skeet Avatar answered Jan 18 '23 22:01

Jon Skeet


You can use params, which lets you specify any amount of arguments

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

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

like image 25
Msonic Avatar answered Jan 19 '23 00:01

Msonic