Is this value a valid year C#

Jamie Dixon picture Jamie Dixon · Dec 3, 2009 · Viewed 12.9k times · Source

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'?

Answer

Deeksy picture Deeksy · Dec 3, 2009

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.