Partha
Partha

Reputation: 479

Cannot convert int to nullable int

In my C# application I want to store null value in an object like:

if (txtClass8Year.Text == "")
{
    distributor.Class8YrPassing = null;
}
else
{
    distributor.Class8YrPassing = Convert.ToInt32(txtClass8Year.Text);
}

But it is not working when I am trying to write the whole statement in one line:

(txtClass8Year.Text == "") ? null : Convert.ToInt32(txtClass8Year.Text);

Thanks in advance.

Partha

Upvotes: 2

Views: 5414

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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);

Upvotes: 2

Related Questions