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.
3 Answers
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
Comments
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#
1 Comment
littlerufe
Would be good to mention that this is no longer a value type (or an
int). Value types cannot be set to null.
int?Nullable<int>or simplyint? i = null;