2

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

1

1 Answer 1

2

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); 
Sign up to request clarification or add additional context in comments.

3 Comments

Nitpicking: casting null to int? is redundant. (int?)null can be simplified to null.
@ZoharPeled On of the return values must make it clear what the return data type of the ternary operator ?: is. Null can be anything. Convert.ToInt32() returns int. Neither implicitely matches int?. Thus you either need to cast the int to an int? or actually descibe what type the null value actually is, hence (int?)null. See Ehsan's two different options above.
@DeeJ.Doena as I said, I was nitpicking :-).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.