Question

What's the best way to check if a string is a valid year using C#?

I currently have a dropdown list that contains the values {'All','2009','2008'} etc, and I want to know whether the selection is one of the dates or the 'All' field.

Currently I'm checking for bool isYearValid = (Year.ToLower() == "all") ? false : true;

How do I check whether the value is a valid year so that I don't have to have this hardcoded check for 'All'?

Was it helpful?

Solution

Given that a year simply needs to be a valid number, you could just use int32.TryParse and then simply check the range based on what range you want the year to be in.

OTHER TIPS

You can try parsing the year as an integer:

int iYear = 0;

if (Int.TryParse(Year, out iYear))
{
  //You have a valid year inside iYear
  //If you are not sure about the dropdown list values,
  //you can of course do more checks for validity. For example:
  //if iYear is in a proper range
}

you could use:

        DateTime dateTime;
        var year = ...
        DateTime.TryParse(string.Format("1/1/{0}", year), out dateTime);

Wouldn't this be better anyway?

bool isYearValid = !string.Equals(Year, "all", StringComparison.OrdinalIgnoreCase);

How about:

<asp:ListItem Value="1900" Text="All" />

That way you don't have to manually check for "All" at the validation point. You still need to check for 1900, when actually implementing this, but there'd definitely be now way to avoid making that a special scenario, anyway.

Other than that, DateTime.TryParse is the proper way to find out if a string representation is a valid date.

Well, no-one's mentioned it, but why not have a symbol for 'All' defined somewhere and use that in both the drop down initialisation and the comparison?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top