Reputation:
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.
Upvotes: 0
Views: 1706
Reputation: 11
Just add ?
to the end of the type
int? nullInt = null;
if (nullInt == null) {
Console.WriteLine("nullInt is null");
}
Upvotes: 1
Reputation: 1040
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#
Upvotes: 1
Reputation: 353
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
Upvotes: 4