I'm currently trying to set an int that is null, similar to how strings can be null. I've tried: int i = null; which returns Cannot convert null to 'int' because it is a non-nullable value type
but string s = null; Is perfectly fine.
Asked
Active
Viewed 954 times
0
-
You need a nullable type. i.e. `int?` – eye_am_groot Jul 25 '19 at 17:11
-
1You'll have to use [`Nullable
`](https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1?view=netframework-4.8) or simply `int? i = null;` – juharr Jul 25 '19 at 17:11 -
[Why do you want a null value type](https://stackoverflow.com/questions/4739213/)? – Dour High Arch Jul 25 '19 at 17:12
-
2You should include the error rather than just saying "doesn't work". – Calum Halpin Jul 25 '19 at 17:13
3 Answers
4
So value types by default can't be set to null, there are however ways to get them to set to null. To solve your issue you would need to do this:
int? i = null;
This comes from the Microsoft docs here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/
Value Types versus Reference Types can be found here: https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type

the_legitTDM
- 353
- 5
- 21
1
You can use question mark to make it nullable, like that:
int? x = null;
Console.WriteLine(x.Value);
This might help: make nullable reference types in c#

SagiZiv
- 932
- 1
- 16
- 38
-
1Would be good to mention that this is no longer a value type (or an `int`). Value types cannot be set to null. – Rufus L Jul 25 '19 at 17:19
1
Just add ?
to the end of the type
int? nullInt = null;
if (nullInt == null) {
Console.WriteLine("nullInt is null");
}

nickStouwn
- 11
- 3