简体   繁体   中英

How can you write assign a default value from an array when the element does not exist?

This situation has always nagged me. Just as an example, suppose a console application expects filepath in as a command line argument.

string first = args[0]; 

but if there are no arguments, then an error will occur. I suppose I could do something like the following:

string first = (args[0]!=null) ? args[0] : "c:\";

What I'm looking for is something a bit more elegant like:

string first = (MyTryParse(args[0],"c:\");

Which I could write as an extension, however that won't work because args[0] will throw an exception before the method can be called.

Also check, if args[0] is null:

public string MyTryParse(string[] args, int index, string defaultVal)
{
    return index < args.Length ? (args[index] ?? defaultVal) : defaultVal
}
...
string first = MyTryParse(args, 0, "c:\");

Pass args instead of args[0]

Try like this

public string MyTryParse(string[] args, string defaultVal) {
    return args.Length > 0 ? args[0] : defaultVal
}

Same approach but using extension method,

public static class Extensioin
{
    public static string MyTryParse(this string[] args, string defaultVal)
    {
        return args.Length > 0 ? args[0] : defaultVal;
    }
}

And using above method something like this,

string first = args.MyTryParse(@"c:\");

LINQ为此已经具有DefaultIfEmpty方法:

string first = args.DefaultIfEmpty("c:\\").First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM