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

Partha
  • 469
  • 2
  • 14
  • 32
  • Possible duplicate of [Conditional operator assignment with Nullable types?](https://stackoverflow.com/questions/75746/conditional-operator-assignment-with-nullablevalue-types) – GSerg Feb 18 '18 at 10:24

1 Answers1

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);
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • 1
    Nitpicking: casting `null` to `int?` is redundant. `(int?)null` can be simplified to `null`. – Zohar Peled Feb 18 '18 at 10:27
  • @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. – Dee J. Doena Feb 18 '18 at 12:22
  • @DeeJ.Doena as I said, I was nitpicking :-). – Zohar Peled Feb 18 '18 at 13:54