Conditional operator assignment with Nullable<value> types?
The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a null and an Int32, and the type can not be determined (there are real reasons it can't just assume Nullable<Int32>).
If you really want to use it in this way, you must cast one of the values to Nullable<Int32> yourself, so C# can resolve the type:
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? (int?)null
: Convert.ToInt32(employeeNumberTextBox.Text),
or
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text),
I think a utility method could help make this cleaner.
public static class Convert
{
public static T? To<T>(string value, Converter<string, T> converter) where T: struct
{
return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
}
}
then
EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);
While Alex provides the correct and proximal answer to your question, I prefer to use TryParse
:
int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
? (int?)value
: null;
It's safer and takes care of cases of invalid input as well as your empty string scenario. Otherwise if the user inputs something like 1b
they will be presented with an error page with the unhandled exception caused in Convert.ToInt32(string)
.