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.

4
  • You need a nullable type. i.e. int? Commented Jul 25, 2019 at 17:11
  • 1
    You'll have to use Nullable<int> or simply int? i = null; Commented Jul 25, 2019 at 17:11
  • Why do you want a null value type? Commented Jul 25, 2019 at 17:12
  • 2
    You should include the error rather than just saying "doesn't work". Commented Jul 25, 2019 at 17:13

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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#

1 Comment

Would be good to mention that this is no longer a value type (or an int). Value types cannot be set to null.
1

Just add ? to the end of the type

int? nullInt = null;
if (nullInt == null) {
Console.WriteLine("nullInt is null");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.