WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

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.

Upvotes: 0

Views: 237

Answers (4)

w.b
w.b

Reputation: 11238

LINQ already has DefaultIfEmpty method for that purpose:

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

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Pass args instead of args[0]

Try like this

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

Upvotes: 1

Jatin Parmar
Jatin Parmar

Reputation: 647

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:\");

Upvotes: 1

Backs
Backs

Reputation: 24913

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:\");

Upvotes: 3

Related Questions