Leron
Leron

Reputation: 9866

Can I define a method which take 1 or N string values as arguments

I'm pretty sure at some point I've read about this and I think it's possible (not very sure though) but I can not recall how to make it. I want to make a validation method which can take take as arguments 1 or many strings which should be validated against the same rules. So basicly what I need is something like this:

public bool CheckMyStringValues (Strings...)
{
//My common logic for all strings
}

And this will be in my base class, then call it from my child classes like :

CheckMyStringValues("firstString")
or
CheckMyStringValues("firstString", "secondSTring")
..
and so on...

Upvotes: 0

Views: 64

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460058

You could use a params array:

public bool CheckMyStringValues (params string[] strings)
{
    foreach(string str in strings)
    {
        if(yourCondition)
        {
            return false;
        }
    }
    return true;
}

You can use it in several ways:

bool result = CheckMyStringValues(); // empty array
result = CheckMyStringValues(null);  // array is null
result = CheckMyStringValues("");    // one empty string in array
result = CheckMyStringValues("firstString"); // one string in array
result = CheckMyStringValues("firstString", "secondString"); // etc ...
result = CheckMyStringValues(new[]{"firstString", "secondString", "thirdString"});

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

public bool CheckMyStringValues (params string[] list)
{
}

This will allow you to invoke that method using CheckMyStringValue("1stString", "2ndString")

Upvotes: 2

xlecoustillier
xlecoustillier

Reputation: 16351

Try :

public bool CheckMyStringValues(params string[] strings)

Upvotes: 3

Related Questions