C# – Console Parameters test

As from my previous post on c++ console parameters, I thought that I would do one with c# (c sharp) as well, just to show the difference in the languages as well.

Compared to c++ where you cannot use the “==” (is equal to) operation because in c++ that is comparing two different memory locations and not the value within the left/right hand variables. Well in c# you can, there is a Equals method as well that you can use, but either or works fine, so in the example code below here is the main part, where I am comparing against a console parameter equalling -h (normally the help)

if (args[i].Equals("-h")) Console.WriteLine("-h option selected(equals)");
if (args[i]=="-h") Console.WriteLine("-h option selected (==)");

both of them are fine to use as you can see from the output at the bottom of the post, both will print out that “-h option selected”, best to use the Equals though.

Here is the full source code

using System;
 
namespace consoletest
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			for (int i = 0; i < args.Length; i++)
			{
				Console.WriteLine("args " + i + " : " + args[i]);								
				if (args[i].Equals("-h")) Console.WriteLine("-h option selected(equals)");
				if (args[i]=="-h") Console.WriteLine("-h option selected (==)");
			}
		}
	}
}

and here is the output using mono as the .Net runtime environment, as you can see both -h has been outputed

mono consoletest.exe -h here
args 0 : -h
-h option selected(equals)
-h option selected (==)
args 1 : here

Console parameters

Someone asked me the other day when you are checking the console parameters for any passing in options how come something like

if (argv[i] == "-t")

does not work, well it does make sense when you look at it, but because the “-t” is actually a char[] (a string) then this would occupy a place in memory and thus you are checking against memory locations which unless you are very very very lucky, this would never come out correct, you need to use the string compare (strcmp) function as below

#include <iostream>
#include <string.h>
 
using namespace std;
 
int main(int argc, char** argv)
{
 for (int i =0 ; i < argc; i++)
 {
// output argument that was passed in.
   cout << argv[i] << endl;
// compare with "-t" option
   if (strcmp(argv[i],"-t")==0) cout << "the -t option" << endl;
 }
 return 0;
}

and the output would be something like

./consolet -t 40
./consolet
-t
the -t option
40