Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

nullable

I have a int i want to save as a int? Is it possible and if so how?

like image 344
radbyx Avatar asked Nov 28 '22 17:11

radbyx


2 Answers

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;
like image 108
Jon Skeet Avatar answered Dec 05 '22 15:12

Jon Skeet


This goes automatic. Lets say you have the following int

int myInt = 5;

Then you can write the following without problems:

int? myNullableInt = myInt;
like image 25
Øyvind Bråthen Avatar answered Dec 05 '22 16:12

Øyvind Bråthen