Click here to Skip to main content
14,978,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to convert command line arguments to char type

I am writing this
string[] ar=Environment.GetCommandLineArgs();
char c =Convert.ToChar(a);

is converting in this way correct?
Updated 2-Mar-13 23:25pm

No. The command line arguments are strings, and they are (effectively) arrays of characters. You cannot convert a string to a character any more than you can convert a shelf of books into a single novel. And your code doesn't even try - it deoesn't even use the arguments themselves!

Depending on what you want to do with the command line argument, you could compare it directly as a string:
foreach(string cmd in Environment.GetCommandLineArgs())
      case "Command1": ProcessCommand1(); break;
      case "Command2": ProcessCommand2(); break;
As the GetCommandLineArgs method return a string array, any element of it is a string. A string[^] is not a character and not a character array, as in C. You can not convert a string to a single char, since it contains many characters. You can however extract any character from it (using indexer or substring[^] method), or convert it to a character array[^].
So it depends on what yo want exactly...

But for parsing command line arguments, you better use a third party library, like this one:[^]
Convert.ToChar(string)[^] coverts only the first char of the string.
You can use string.ToCharArray[^] to convert all the char in a string to char array eg:
string delimStr = " ,.:";
char [] delimiter = delimStr.ToCharArray();

so you make a decision on how your arguments are passed and how to use these methods to parse your arguments.
You really need a command-line parsing library and well-defined command line syntax per application, instead of "character" or any other ad-hoc stuff. I can offer my open-source code provided in my CodeProject article Enumeration-based Command Line Utility[^].

This library is especially easy to use and the usage is less error-prone. Another good library is recommended in my article.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900