You need to cast the int
result back to Nullable<int>
as the int
in not the same type as int?
and they can't be implicitly casted to and from,so we need to be specific there:
distributor.Class8YrPassing = (txtClass8Year.Text == "")
? null
: (int?)Convert.ToInt32(txtClass8Year.Text);
or alternatively you can make the null
casted to int?
that would also work:
distributor.Class8YrPassing = (txtClass8Year.Text == "")
? (int?)null
: Convert.ToInt32(txtClass8Year.Text);
As for ternary operator we need to make sure that in both cases same type is getting returned, otherwise the compiler would give the error like above.
and a suggestion is that more better would be to use String.IsNullOrEmpty
method instead of checking ""
literal string:
distributor.Class8YrPassing = String.IsNullOrEmpty(txtClass8Year.Text) || String.IsNullOrWhiteSpace(txtClass8Year.Text)
? null
: (int?)Convert.ToInt32(txtClass8Year.Text);