0

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 Answers3

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
  • 1
    Would 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