Really easy C# question

Soldato
Joined
17 Jan 2007
Posts
8,944
Location
Manchester
Okay, I'm pretty embarrassed by the fact I've been outsmarted by a handful of lines of code. I'm trying to follow this guide to get myself started with C#. The guide is quite good, but I'm stumped on part of it. Whether its because it's late or the beer I'm doing my nut in trying to work this out.

I'm up to the "Adding things to do" section of the guide linked to above, which is basically passing an argument from the command line and doing something with it. I keep getting an error when trying to run what I've written. I've boiled it down somewhat from the guide for simplicity - the error is the same:

Code:
using System;
//using System.IO;

namespace toDoList
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			
			if (args[0] == "add") 
			{
				Console.WriteLine("Hello");
			} 
			else 
			{
				Console.WriteLine("Goodbye");
			}
			
		}
	}
}

And the error is:

Code:
Unhandled Exception: System.IndexOutOfRangeException: Array index is out of range.
  at toDoList.MainClass.Main (System.String[] args) [0x00000] in /home/mh/toDoList/toDoList/Main.cs:16

I should be able to do "$ mono ./toDoList.exe add" to make it spit out "Hello" and anything else to spit out "Goodbye".

I'm going to go to bed now and hope someone has pointed out the obvious to me when I check back tomorrow.

Cheers guys & girls. :o
 
Argh still no worky, I've tried all the suggestions. Interestingly if I use:

Code:
if (args.Length != 0)

or

Code:
foreach (string arg in args)

... the program will compile (I thought we'd cracked it), but when I come to run it with the argument "add" it throws out the exception error. i.e.

Code:
mh@mh-lin:~/toDoList/toDoList/bin/Debug$ mono toDoList.exe add

Unhandled Exception: System.IndexOutOfRangeException: Array index is out of range.
  at toDoList.MainClass.Main (System.String[] args) [0x00000]

Same error, different place. :(

A real head scratcher this one. I've made a post at the end of that guide, whether someone responds to it is another matter. I'm still open to more suggestions, even if you just post how you would do it might give me ideas. Cheers all.
 
@lokkers - it's encouraging that it works in Windows. Perhaps its my version of Mono? The Help > About says it is Mono version 1.0 which sounds iffy but surely there can't be a bug for something so simple. Did you copy/paste the code from my first post exactly?

@Dj_Jestar - that works fine. See output:

Code:
mh@mh-lin:~/toDoList/toDoList/bin/Debug$ mono toDoList.exe apple bear car
args size: 3
args:
=====
apple
bear
car

Press any key to continue...

mh@mh-lin:~/toDoList/toDoList/bin/Debug$

I've actually already completed a similar task for printing out elements in an array, it just seems that whenever you try to reference it directly it throws an exception.

Cheers guys I really appreciate the help.
 
Back
Top Bottom