4

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

3
  • Save? Where? Consider adding a little more (e.g. any) context to your question. Commented Feb 15, 2012 at 9:33
  • Well I tryed this int? status2 = new Nullable<int>(someThing); The idea was actually not all that bad, I can see now that it work. I just had a error with the someThing, and I thought the error was the new Nullable<int> code I used. So I tricked my self :( Commented Feb 15, 2012 at 9:55
  • someThing come from a textbox. I don't remember the error but i think i was a parsing error or another error higher up in the code that confused me. Commented Feb 15, 2012 at 9:57

2 Answers 2

23

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

1 Comment

Thanks to you and Øyvind for the answer.
2

This goes automatic. Lets say you have the following int

int myInt = 5; 

Then you can write the following without problems:

int? myNullableInt = myInt; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.