Reputation: 24572
I am trying to set the value of sequence to null if it's null or to a value
var sequence = parameters[11].Value != DBNull.Value ?
(int)parameters[11].Value : null;
But getting this message:
Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''
Can anyone give me advice on this one? Note that I need the (int) cast as the parameters are returned as objects.
Upvotes: 1
Views: 422
Reputation: 9530
I don't know why nobody used default keyword .. it is very important and powerful key in c#
.. you better start use of it .. in some critical generic situation .. it will play very vital role for you..
var sequence = parameters[11].Value != DBNull.Value ? Convert.ToInt32(parameters[11].Value) : default(int?);
Upvotes: 0
Reputation: 30813
You may want to change the direct casting to the Convert.ToInt32
int? sequence = parameters[11].Value != DBNull.Value ?
new Nullable<int>(Convert.ToInt32(parameters[11].Value.ToString())) : null;
Also, since you want to assign either int
or null
, then the data type must be nullable
(i.e. int?
)
Upvotes: 3
Reputation:
There are two problems: you have not declared the variable's type, and the compiler cannot work it out for itself.
int? sequence = (parameters[11].Value != DBNull.Value
? (int)parameters[11].Value
: null);
This will compile ok, because the compiler can convert both int and null to Nullable<int>
Upvotes: 1
Reputation: 2778
You are casting your parameters[11].Value
to int
which does not seem to match the type of parameters[11].Value
which you are setting.
Try to omit the (int)
.
Upvotes: 1
Reputation: 2243
assuming that var sequence
is type of int?
you can do
int? sequence = parameters[11].Value != DBNull.Value ? (int?)parameters[11].Value : null;
Upvotes: 4