How to Convert C# Nullable Int to Int

Convert between nullable int and int

You have to cast null as well:

int? l = lc.HasValue ? (int)lc.Value : (int?)null; 

By the way, that's one of the differences between the conditional operator and an if-else:

if (lc.HasValue)
l = (int)lc.Value;
else
l = null; // works

The relevant C# specification is 7.14 Conditional operator:

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

  • If x has type X and y has type Y then

    • If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
    • If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
    • Otherwise, no expression type can be determined, and a compile-time error occurs.

Since int is not convertible to null implicitly and vice-versa you get a compiler error. But you could also cast the enum to int? instead of int which is convertible. Then the compiler can derive the type and it'll compile:

int? l = lc.HasValue ? (int?)lc.Value : null; // works also

or, as Sergey has mentioned in his answer, directly:

int? l = (int?)lc;

How to convert from int to int?, in C#?

There's an implicit conversion:

int nonNullable = 5;
int? nullable = nonNullable;

(This is given in section 6.1.4 of the C# specification.)

The reverse operation is unsafe, of course, because the nullable value could be null. There's an explicit conversion, or you can use the Value property:

int? nullable = new int?(5); // Just to be clear :)

// These are equivalent
int nonNullable1 = (int) nullable;
int nonNullable2 = nullable.Value;

Cannot convert int to nullable int

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

Convert null field to zero before converting to int?

You could do this:

var LYSMKWh =
resultsDT.Rows[currentRow]["LYSMKWh"].Equals(DBNull.Value)
? 0
: Convert.ToInt32(resultsDT.Rows[currentRow]["LYSMKWh"]);

convert int to nullable int?

That To code seems to be you trying to construct a Constant of nullable type when given a value of non-nullable type but that is not at all the right way to go about this. The way you're trying to do this indicates that you have a misunderstanding about how boxed value types work.

That error message indicates that you are constructing a binary operator expression tree node which has as its operands an expression node of nullable int type and an expression node of int type. That's not legal; they have to be both nullable int. What you should be doing is wrapping the non-nullable int expression tree node in a Convert expression tree node which converts it to a nullable int, and then pass that to the binary operator expression tree node constructor.

That is, this is wrong:

var someIntExpr = Expression.Constant(123, typeof(int));
var someNubIntExpr = Expression.Constant(null, typeof(int?));
var badEq = Expression.Equal(someIntExpr, someNubIntExpr);

This is right:

var goodEq = Expression.Equal(Expression.Convert(someIntExpr, typeof(int?)),  someNubIntExpr);

So why is what you're doing wrong?

You have a method To<T> which returns a T. It correctly takes in an int and returns the equivalent int?. So then what? You pass that to Expression.Constant, which boxes the nullable int into a boxed int, and then makes a constant out of that. You believe that there is such a thing as a boxed nullable value type, but there is not! A nullable value type boxes either to a null reference or to a boxed non-nullable value type.

So you could also solve your problem by not doing any of this crazy stuff in the first place. If you have a boxed int in hand, and you need a constant expression tree node of nullable type, just provide the type.

Expression.Constant(someBoxedIntValue, typeof(int?))

Done. So: wrapping up, you have two solutions:

  • If you have a boxed int in hand, pass it and the nullable value type you want to the Constant factory, or
  • if you have an expression node of type int in hand then use the Convert expression node factory, and pass it and the desired type to that.

Both will give you back an expression node of the correct type to be compared to another nullable int.

How to set null value to int in c#?

In .Net, you cannot assign a null value to an int or any other struct. Instead, use a Nullable<int>, or int? for short:

int? value = 0;

if (value == 0)
{
value = null;
}

Further Reading

  • Nullable Types (C# Programming Guide)

Why can't a nullable int be implicitly conversion to an int ? Technical reason or design choice?

The code you have doesn't add an implicit conversion from the .NET's nullable int to .NET's int. It creates a whole new type, called Int32, in the System namespace, but as it's in a different assembly than Core.dll, it's a different type. (Take a look at typeof(int).FullName and typeof(int32).FullName to see this.)

The code you showed to try to test this implicit conversion is set up so that it's trying to convert the system's nullable type to your own new type, and since you created such an implicit conversion, it succeeds. It fails when you use the system type instead of your own new type because there is no implicit conversion between those types.

You cannot create implicit (or explicit) conversions for types from outside the definition of one of those types, and since you can't access the source of either Nullable or the .NET Int32, you can't add an implicit conversion.

Convert nullable int to int in linq query return anonymous type

First there is one '=' missing in your equals operator. Then, if You want to compare an int with an int? you can use the Null Coalescing operator ?? to provide a default value for the null-case , then cast it to an int:

h.Kod == (a.KodH ?? 0)


Related Topics



Leave a reply



Submit