0

I'm missing something, how do I make this work?

var now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths( -14 ).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ] == String.Empty ? now.ToShortDateString();

Basically when the page loades if sd and/or ed is blank, then fill the date with my pre-defined stuff.

3 Answers 3

5

You are forgetting a : and the part after it.

The conditional operator has three parts:

  • predicate (Request.QueryString["sd"] == String.Empty)
  • true branch
  • false branch

You are missing the false branch syntax and value.

I would write it as:

string loadStartDate = string.IsNullOrWhitespace(Request.QueryString["sd"])
                       ? now.AddMonths( -14 ).ToShortDateString()
                       : Request.QueryString["sd"];

Note:

string.IsNullOrWhitespace is new to .NET 4.0, so use string.IsNullOrEmpty for prior versions.

Sign up to request clarification or add additional context in comments.

8 Comments

Yup; and Request.QueryString[] will return null (rather than String.Empty) if no value at all was submitted.
@p.campbell - Indeed... though if a string is needed, one doesn't need to roundtrip. Missed that.
Thanks for this! Was wondering what I was missing. Thank you for the through explanation to. :)
Am I missing a using statement at top? It is saying 'string' does not contain a definition for 'IsNullOrWhitespace'
@JamesWilson - I added a note about that... It is a .NET 4.0 addition. Use string.IsNullOrEmpty instead if not on 4.0 yet.
|
1

It should be like:

string loadStartDate = Request.QueryString["sd"] == String.Empty ? now.AddMonths
( -14 ).ToShortDateString():SOME OTHER VALUE;

Comments

1

The syntax for the conditional operator is:

condition ? truevalue : falsevalue

You are missing the colon and the value for when the conditon is false.

You can use the conditional operator for this, but then it gets a little repetetive. Just do like this:

DateTime now = DateTime.Now;
string loadStartDate = Request.QueryString["sd"];
if (String.IsNullOrEmpty(loadStartDate)) loadStartDate = now.AddMonths(-14).ToShortDateString();
string loadEndDate = Request.QueryString[ "ed" ];
if (String.IsNullOrEmpty(loadEndDate)) loadEndDate = now.ToShortDateString();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.