I'm trying to convert command line arguments to different formats. For example, if I'm trying to get a specific user, it would be GetUser=UserName
, but I also have methods that don't need the equals sign, such as GetAllUsers
. Right now I'm currently splitting on the =
but I don't need to do that for all commands. I tried setting it to a conditional, where if =
is detected, it will split, otherwise it will just take the argument as a string, but I'm getting Cannot implicitly convert type 'string' to 'System.Collections.Generic.Dictionary<string, string>
Code:
public static Dictionary<string, string> ParseArgs(string[] args)
{
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string arg in args)
{
string[] parts = arg.Split('=');
if (parts.Length > 1)
{
results[parts[0]] = parts[1];
continue;
}
else
{
results = Convert.ToString(arg);
}
}
return results;
}
results = Convert.ToString(arg);
think about what this line is doing, what the type ofresults
is, and why it's a problem. – Ian Kemp Jan 13 '20 at 20:58CommandLineParser
library. Git here - github.com/commandlineparser/commandline. It makes parsing command line args much simpler. The problem you are currently facing is trying to assign a string to a dictionary type. That obviously will not work. You could probably doresults.Add(arg, arg)
to have the key be the same as the value, but thats pretty spaghetti to me. You'd be much better off using the correct tool for the job. – user12447201 Jan 13 '20 at 20:59if/else
withresults[parts[0]] = parts.Length > 1 ? parts[1] : "";
– Rufus L Jan 13 '20 at 21:07