0
List<string> arguments = new List<string>(Environment.GetCommandLineArgs().Skip(1).Take(4));
int variant = consoleOptions.HandleInput(arguments);

public int HandleInput(List<string> input)
{
        int variant = 0;

        //for (int i = 0; i < input.Count; i++)
        //{
        //    if (input[i].Contains("-s"))
        //    {
        //         variant = 1; 
        //    }
        //}

        if (input[0].Contains("-s"))
        {
            variant = 1; 

            if (!String.IsNullOrWhiteSpace(input[1]) && !String.IsNullOrWhiteSpace(input[2]))
            {
                variant = 2;        
            }

            if (!String.IsNullOrWhiteSpace(input[3]))
            {
                variant = 3;
            }
        }
        return variant;
}

I'm starting my application from Commandline. Then I get a List of Strings (max 4).

What I want to do now is:

if the first String in List is "-s" then variant = 1

if the second and third string isn't Empty then variant = 2

if the fourth string isn't Empty then variant = 3

I tried some things (Code above), but the problem is, if I only get the first String (one item), The Compiler crashes on other place (checking Second string, cause Index not accessible)..

What would be the best method?

3
  • You have to learn else statement Commented Feb 7, 2012 at 12:03
  • You might want to try a command line parsing lib (commandline.codeplex.com) instead of re-inventing the wheel. Commented Feb 7, 2012 at 12:12
  • I really tried to use it, but I didn't find any benefits, its also to complicated for me Commented Feb 7, 2012 at 12:44

2 Answers 2

1

The Take(4) doesn't guarantee that you'll have 4 elements, it just means you won't have more than 4. So you have to check the list length.

if (input.Count >= 1 && input[0].Contains("-s"))
{
    return 1;
}
if (input.Count >= 3)
{ 
    return 2;
}
if (input.Count >= 4)
{
    return 3;
}

return 0; //what do you return if none of the conditions are met?
Sign up to request clarification or add additional context in comments.

2 Comments

Lenght was not possible, so I used .Count
@eMi oh you're right. When I first wrote the answer, I thought it was an array for some reason.
0

you try some thing like this.

 if (input[0].Contains("-s"))
        {
            variant = 1; 
        }
 if (!String.IsNullOrWhiteSpace(input[1]) && !String.IsNullOrWhiteSpace(input[2]))
            {
                variant = 2;        
            }
 if (!String.IsNullOrWhiteSpace(input[3]))
            {
                variant = 3;
            }
        return variant;

1 Comment

This doesn't address the real problem that the list won't have the right number of elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.